How can I make a UITextField the first responder, correctly? (Tried 3 methods)

222 Views Asked by At

Here's the setup:

SNController is an NSObject and it has inside:

  1. UIView
  2. UITextField
  3. UISegmentedControl
  4. UILabel
  5. UIButton

The view is the same as the view inside the ViewController.

One can be visible at the time. When the UITextField is visible (alpha = 1.0) all the others are invisible (alpha = 0.0).

(1) I perform an animation and I want the text field:

UITextField *textField;

to become the first responder while the animation happens:

[textField becomeFirstResponder];

[UIView animateWithDuration: ...];

Unfortunately it doesn't work.

I've logged the text field and it showed that it cannot become the first responder and I have no idea why...

I've tried another two methods but none of them worked so far:

(2) A complicated way to communicate with the ViewController from the SNController:

Inside the SNController.h/.m:

@property (nonatomic, copy) void(^eventCallBack)();

if (self.eventCallBack) {

    self.eventCallBack();
}

Inside the ViewController.m:

__weak ViewController *self_ = self;

self.restoration.controller.eventCallBack = ^(){

    [self_.restoration.controller.textField becomeFirstResponder];
};

(3) I also tried these methods from inside the SNController:

[self.textField performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.0];

[self.textField performSelectorOnMainThread:@selector(becomeFirstResponder) withObject:nil waitUntilDone:YES];

It just won't give up, it doesn't become the first responder no matter what.

Any ideas?

1

There are 1 best solutions below

0
On

I realised there was a mistake. There isn't a UITextField inside the SNController but a UIView subclass named SNTextField.

I implemented this method where the UITextField was initialised:

- (void)activateKeyboard
{
    [self.textField becomeFirstResponder];
}

and it worked!