2014-11-02 49 views
0

在我的类中使用shouldChangeCharactersInRange来捕获UITextField在uitableview中。shouldChangeCharactersInRange返回UITextField的第二个字符

问题是它没有得到第一个输入值并从第二个开始。

如果我输入 “123”,它仅示出了 “12”

这是我的代码:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    UITextField *utx = (UITextField *) textField; 

    UITableViewCell *cell = (UITableViewCell*)utx.superview.superview.superview; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    UITextField *utxtest = (UITextField *)[cell.contentView viewWithTag:20]; 

    NSLog(@"utxtest %@", utxtest.text); 
     NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet]; 

     NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; 

     return [string isEqualToString:filtered]; 

    return YES; 
} 

,在我的tableview:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    UITextField * utxtest = (UITextField *)[cell.contentView viewWithTag:20]; 
    utxtest = self; 
    return cell; 
} 
+0

当你说,而不是'123'它显示'23',那是什么?在NSLog语句中还是在UITableViewCell中? – AMI289 2014-11-02 10:30:32

+0

它在nslog输出“utxtest 23” – 2014-11-02 10:32:54

+0

它显示如果你NSLog的utx变量是什么? – AMI289 2014-11-02 10:44:22

回答

1

我与的UITextField和测试将NSLog放在shouldChangeCharactersInRange上,就像你所做的一样。输入“123”,nslog显示“12”,而不是“23”,正如你所说。

所以首先,重新检查你的结果。如果它仍然是“23”,我不知道它

如果它是“12”,我认为问题是你把您的NSLog上shouldChangeCharactersInRange它负责输入文本验证。文本字段仅分配新值,仅在AFTER此方法返回YES。如果返回NO,则该值不会改变。而当然,当你仍然处在方法的中间时,textfield.text仍然返回旧值。

+0

非常感谢,我修好了,你的权利。这是一个错字,结果是“12”而不是“23”。所以有什么办法可以捕获完整插入文本shouldChangeCharactersInRange内? – 2014-11-02 10:49:32

+1

我没有XCode在这里测试,但你可以尝试NSString * tmpNewValue = [utxtest.text stringByReplacingCharactersInRange:range withString:string]; //这里的字符串是replacementString的值。请记住,您只需获取新的临时值,不要在此方法中更改utxTest的值,这会导致副作用 – meaholik 2014-11-02 14:42:05

相关问题