我有一个的UITextField在MyCustomUIView类时的UITextField失去焦点,我想隐藏字段和显示别的东西来代替。

UITextField委托设置为通过IB至MyCustomUIView和我也有“难道结束对退出”和“编辑了,结束”指向IBAction内的MyCustomUIView方法事件。

@interface MyCustomUIView : UIView { 

IBOutlet UITextField    *myTextField;

}

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

@end

然而,无论这些事件似乎当的UITextField失去焦点被炒鱿鱼。你怎么陷阱/看此事件?

UITextField的委托,所以我接收MyCustomUIView消息完成时关闭该键盘被设置为textFieldShouldReturn

但是,我也有兴趣在当用户按下屏幕上的其他一些区域是确定(比如另一个控制或只是空白区域)和文本字段已失去焦点。

有帮助吗?

解决方案

我相信你需要指定您的视图为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;
}

其他提示

尝试使用委托下面的方法:

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

这是为我工作。

使用的 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;
}

您可能需要子类UITextField并覆盖resignFirstResponderresignFirstResponder将被称为正如文本字段失去焦点。

我想你已经实现UIKeyboardDidHideNotification在这种情况下,您

使用类似的代码

[theTextField resignFirstResponder];

删除该代码。

textFieldShouldReturn方法也相同的代码写操作。这也失去焦点。

有关那些在夫特与此挣扎。我们添加一个手势识别到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()
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top