UITextField失去焦点事件

时间:2009-07-15 18:48:50

标签: ios objective-c uitextfield uitextfielddelegate

我在MyCustomUIView类中有一个UITextField,当UITextField失去焦点时,我想隐藏该字段并显示其他内容。

UITextField的代表通过IB设置为MyCustomUIView,我还有'退出时已结束'和'编辑已结束'事件,指向IBAction内的MyCustomUIView方法{1}}。

@interface MyCustomUIView : UIView { 

IBOutlet UITextField    *myTextField;

}

-(IBAction)textFieldLostFocus:(UITextField *)textField;

@end

然而,当UITextField失去焦点时,这些事件似乎都没有被触发。你如何陷阱/寻找这个事件?

UITextField的代理设置为MyCustomUIView,因此我收到textFieldShouldReturn消息,以便在完成后关闭键盘。

但我感兴趣的还在于确定用户何时按下屏幕上的其他区域(比如另一个控件或只是空白区域)并且文本字段失去焦点。

6 个答案:

答案 0 :(得分:27)

尝试使用委托代替以下方法:

- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"Lost Focus for content: %@", textField.text);
    return YES;
}

这对我有用。

答案 1 :(得分:12)

我认为您需要将您的视图指定为UITextField委托,如下所示:

@interface MyCustomUIView : UIView <UITextFieldDelegate> { 

作为一个额外的好处,这就是当你按下“完成”或返回按钮时键盘离开的方式,具体取决于你如何设置该属性:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
  //This line dismisses the keyboard.       
  [theTextField resignFirstResponder];
  //Your view manipulation here if you moved the view up due to the keyboard etc.       
  return YES;
}

答案 2 :(得分:4)

resignFirstResponder 解决方案的问题在于,它只能由显式的键盘 UITextField 事件触发。 我还在寻找一个“丢失焦点事件”来隐藏键盘,如果在文本区域外的某个地方被轻拍。 我遇到的唯一紧密而实用的“解决方案”是,禁用其他视图的交互,直到用户完成编辑(在键盘上完成/返回)但仍然能够在文本字段之间跳转以进行更正每次都需要滑出键盘。

以下代码段可能对想要做同样事情的人有用:

// disable all views but textfields
// assign this action to all textfields in IB for the event "Editing Did Begin"
-(IBAction) lockKeyboard : (id) sender {

    for(UIView *v in [(UIView*)sender superview].subviews)
        if (![v isKindOfClass:[UITextField class]]) v.userInteractionEnabled = NO;
}

// reenable interactions
// assign this action to all textfields in IB for the event "Did End On Exit"
-(IBAction) disMissKeyboard : (id) sender {

    [(UIResponder*)sender resignFirstResponder]; // hide keyboard

    for(UIView *v in [(UIView*)sender superview].subviews)
        v.userInteractionEnabled = YES;
}

答案 3 :(得分:2)

您可能必须继承UITextField并覆盖resignFirstResponder。 <{1}}将被调用,就像文本字段失去焦点一样。

答案 4 :(得分:1)

我认为你已经实施了UIKeyboardDidHideNotification,在这种情况下你已经

使用像

这样的代码
[theTextField resignFirstResponder];

删除此代码。

同样的代码也用textFieldShouldReturn方法编写。这也失去了重点。

答案 5 :(得分:0)

对于那些在Swift中苦苦挣扎的人。我们在ViewController的视图中添加了一个手势识别器,以便在点击视图时我们关闭文本字段。重要的是不要取消后续点击视图。

Swift 2.3

    override func viewDidLoad() {
        //.....

        let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
        //this line is important
        viewTapGestureRec.cancelsTouchesInView = false
        self.view.addGestureRecognizer(viewTapGestureRec)

         //.....
    }

    func handleViewTap(recognizer: UIGestureRecognizer) {
        myTextField.resignFirstResponder()
    }