shouldChangeCharactersInRange从UITextField返回第二个字符

时间:2014-11-02 10:18:18

标签: ios objective-c uitableview

我在我的类上使用shouldChangeCharactersInRange来捕获uitableview中的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;
}

1 个答案:

答案 0 :(得分:1)

我已经使用UITextField进行了测试,并将NSLog放在了shouldChangeCharactersInRange上。输入" 123",nslog显示" 12",不" 23"正如你所说。

首先,重新检查一下你的结果。如果它仍然是" 23",我根本不知道

如果是" 12",我认为问题是你将NSLog放在 shouldChangeCharactersInRange 上,它负责输入文本验证。只有 AFTER 此方法返回YES时,Textfield才会被赋予新值。如果返回NO,则值不会改变。当然,当你仍然在方法的中间时,textfield.text仍然会返回旧的值。