UITextField shouldChangeCharactersInRange会发射两次?

时间:2015-09-14 14:45:37

标签: ios objective-c uitextfield

我有一个表格视图。在cellForRowAtIndexPath我有一个单元格,在那个单元格中有UITextField。我像这样设置textfield的委托:cell.textField.delegate = self;。我需要在第三个字符上调用我的API。因此,当用户在文本字段中键入3个字符时,API将被调用shouldChangeCharactersInRange

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   if (textField.text.length >= 2) {
     NSString *substring = [NSString stringWithString:textField.text];
     substring = [substring
                 stringByReplacingCharactersInRange:range withString:string];
    [API CALLED WITH BLOCK WITH TEXTFIELD TEXT AS PARAMETER:substring];
 }
  return YES;
}

问题在于,当我输入例如“abc”shouldChangeCharactersInRange时,第一次调用,参数是“abc”。第二次,shouldChangeCharactersInRange再次被调用,我的文本字段有另一个添加的字符,我没有输入,它总是复制的最后一个字符。所以在这个例子中,它发送“abcc”。你知道吗,问题是什么?

2 个答案:

答案 0 :(得分:3)

在该委托方法中设置断点有时会导致该方法被触发两次。尝试删除此处或API方法中的任何断点,然后重新测试。

这可以很容易地复制。创建一个新项目,添加UITextField出口并将委托设置为您的控制器。在控制器中实施textField:shouldChangeCharactersInRange:并在NSLog语句或return YES上设置断点。有时,在告诉调试器继续之后,将生成第二次击键并再次点击您的委托方法。

答案 1 :(得分:0)

I would recommend using a textFieldDidChange instead as this occurs after the text has been typed so you don't have to deal with appending strings. From there you can just check 'text.lenght >=3' to fire your API call.

You can add the event like this:

[textField addTarget:self 
              action:@selector(textFieldDidChange:) 
    forControlEvents:UIControlEventEditingChanged];

EDIT: This code works for me. I sent up the delegate in the cell class.

#import "AnotherTableViewCell.h"

@implementation AnotherTableViewCell

@synthesize myTextField = _myTextField;

- (void)awakeFromNib {
    // Initialization code

    _myTextField.delegate=self;

    [_myTextField addTarget:self
                  action:@selector(textFieldDidChange:)
        forControlEvents:UIControlEventEditingChanged];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)textFieldDidChange:(UITextField*)textField{
    if (textField.text.length>=3) {
        NSLog(@"Text >= 3: %@",textField.text);
    }
}

@end