简体   繁体   English

如何正确地将UITextField设置为第一响应者? (尝试了3种方法)

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

Here's the setup: 设置如下:

SNController is an NSObject and it has inside: SNController是一个NSObject ,它具有以下内容:

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

The view is the same as the view inside the ViewController . 该视图与ViewController中的视图相同。

One can be visible at the time. 当时可以看到一个。 When the UITextField is visible (alpha = 1.0) all the others are invisible (alpha = 0.0). UITextField可见时(alpha = 1.0),所有其他UIUI都不可见(alpha = 0.0)。

(1) I perform an animation and I want the text field: (1)我执行动画,并且想要文本字段:

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 : (2)一种从SNControllerViewController通信的复杂方法:

Inside the SNController.h/.m : SNController.h / .m内部:

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

if (self.eventCallBack) {

    self.eventCallBack();
}

Inside the ViewController.m : 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 : (3)我还从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? 有任何想法吗?

I realised there was a mistake. 我意识到有一个错误。 There isn't a UITextField inside the SNController but a UIView subclass named SNTextField. SNController内部没有UITextField,而是一个名为SNTextField的UIView子类。

I implemented this method where the UITextField was initialised : 在初始化UITextField的地方实现了此方法:

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

and it worked! 而且有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM