在UITextField上执行select器“selectAll”时出现奇怪的问题
我正面临着最恶劣的bug(在我的应用程序或IOS 7.1中)。 几个小时后,我设法创build了一个简单的应用程序,演示了这个问题。
两个UITextField – 从界面构build器拖放并连接到t1,t2。 ViewController:
@implementation ViewController @synthesize t1; @synthesize t2; #pragma mark - UITextFieldDelegate -(void)textFieldDidBeginEditing:(UITextField *)iTextField { NSLog(@"textFieldDidBeginEditing"); [iTextField performSelector:@selector(selectAll:) withObject:iTextField afterDelay:0.0]; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { return YES; } - (void)viewDidLoad { [super viewDidLoad]; t1.delegate = self; t2.delegate = self; } @end
当同时点击t1和t2 时 ,两个textField都会成为无限循环中的第一个响应者! 当省略了PerformSelector语句或textField:shouldChangeCharactersInRange:实现时,问题就消失了。
有人可以解释为什么会发生?
编辑:同时将每个UITextField
的exclusiveTouch属性设置为:YES以防止它们同时编辑。
- (void)viewDidLoad { [super viewDidLoad]; t1.exclusiveTouch = YES; t2.exclusiveTouch = YES; t1.delegate = self; t2.delegate = self; } - (void)textFieldDidBeginEditing:(UITextField *)iTextField { [iTextField performSelector:@selector(selectAll:) withObject:nil afterDelay:0.0]; }
或者更简单地不使用exclusiveTouch属性:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)iTextField { if (iTextField == t1 && t2.isFirstResponder == NO) { return YES; } else if (iTextField == t2 && t1.isFirstResponder == NO) { return YES; } return NO; }