0

I am facing the the wierdest bug (ether in my app or in IOS 7.1) ever. After many hours I managed to create a simple app that demonstrate the problem.

Two UITextField - Dragged and dropped from interface builder and wired to t1, t2. the 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

When tapping on t1 and t2 at the same time, both textFields become first responder in an endless loop! When omitting ether the PerformSelector statement or the textField:shouldChangeCharactersInRange: implementation, problem is gone.

Can someone explain why does it happen?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Yony
  • 680
  • 1
  • 9
  • 20
  • What about trying `[iTextField selectAll:self];`? – rmaddy Jul 12 '14 at 04:04
  • It causing the problem to vanish but creating another one. If the textField contain text, tapping on the textField select all text. When dismissing the keyboard and tapping again, the text doesn't get selected again. – Yony Jul 12 '14 at 04:12

2 Answers2

1

Edit: Also set the exclusiveTouch property of each UITextField to: YES to prevent them from editing at the same time.

- (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];
}

Or more simply without using the exclusiveTouch properties:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)iTextField
{
    if (iTextField == t1 && t2.isFirstResponder == NO)
    {
        return YES;
    }
    else if (iTextField == t2 && t1.isFirstResponder == NO)
    {
        return YES;
    }

    return NO;
}
klcjr89
  • 5,862
  • 10
  • 58
  • 91
0

I try to use the selectedTextRange property to instead of selectAll, it makes the endless loop's problem gone.

func textFieldDidBeginEditing(_ textField: UITextField) {
    DispatchQueue.main.async {
        let begin = textField.beginningOfDocument
        let end = textField.endOfDocument
        textField.selectedTextRange = textField.textRange(from: begin, to: end)
    }
}