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

时间:2014-12-15 18:35:23

标签: ios objective-c uitextfield uiresponder becomefirstresponder

以下是设置:

SNController 是一个 NSObject ,里面有:

  1. 的UIView
  2. 的UITextField
  3. UISegmentedControl
  4. 的UILabel
  5. 的UIButton
  6. 视图与 ViewController 中的视图相同。

    当时可以看到一个。当 UITextField 可见时(alpha = 1.0) 所有其他都是不可见的(alpha = 0.0)。

    (1)我执行动画,我想要文本字段:

    UITextField *textField;
    

    成为动画发生时的第一个响应者:

    [textField becomeFirstResponder];
    
    [UIView animateWithDuration: ...];
    

    不幸的是它不起作用。

    我已经记录了文本字段,它表明它不能成为第一个响应者,我不知道为什么......

    我尝试了另外两种方法,但到目前为止还没有一种方法:

    (2)与 SNController 中的 ViewController 进行通信的复杂方式:

    SNController.h / .m 中:

    @property (nonatomic, copy) void(^eventCallBack)();
    
    if (self.eventCallBack) {
    
        self.eventCallBack();
    }
    

    ViewController.m 中:

    __weak ViewController *self_ = self;
    
    self.restoration.controller.eventCallBack = ^(){
    
        [self_.restoration.controller.textField becomeFirstResponder];
    };
    

    (3)我也在 SNController

    中尝试了这些方法
    [self.textField performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
    
    [self.textField performSelectorOnMainThread:@selector(becomeFirstResponder) withObject:nil waitUntilDone:YES];
    

    它只是不会放弃,无论如何都不会成为第一个响应者。

    有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我意识到有一个错误。 SNController中没有UITextField,而是一个名为SNTextField的UIView子类。

我实现了 UITextField初始化的方法:

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

它有效!