我想知道如何使键盘消失时,用户触摸以外的UITextField。


当前回答

只是使用这段代码在您的.m文件,它将辞职的文本字段,当用户点击文本字段之外。

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  [textfield resignFirstResponder];
 }

其他回答

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
     view.endEditing(true)

     }
}
- (void)viewDidLoad
{
    [super viewDidLoad]; 

UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
                                                          initWithTarget:self
                                                          action:@selector(handleSingleTap:)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
    [singleTapGestureRecognizer requireGestureRecognizerToFail:singleTapGestureRecognizer];

    [self.view addGestureRecognizer:singleTapGestureRecognizer];
}

- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
    [self.view endEditing:YES];
    [textField resignFirstResponder];
    [scrollView setContentOffset:CGPointMake(0, -40) animated:YES];

}

如果我得到你的权利,你想辞职键盘狡猾敲在文本字段之外,但你没有你的文本字段的引用。

试试这个;

Take global textField, lets call it reftextField Now in textFieldDidBeginEditing set referenced text field to - (void) textFieldDidBeginEditing:(UITextField *)textField{ reftextField = textField; } Now you can happily use on any button clock, (adding a transparent button on begin editing recomended) - (void)dismissKeyboard { [reftextField resignFirstResponder]; } Or for resigning done button try this. //for resigning on done button - (BOOL) textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; }

这个怎么样:我知道这是一个老帖子。它可能会帮助某些人:)

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
    NSArray *subviews = [self.view subviews];
    for (id objects in subviews) {
        if ([objects isKindOfClass:[UITextField class]]) {
            UITextField *theTextField = objects;
            if ([objects isFirstResponder]) {
                [theTextField resignFirstResponder];
            }
        } 
    }
}

你需要添加一个UITapGestureRecogniser并将其分配给视图,然后在它的选择器上的UITextField上调用resign first responder。

代码:

在viewDidLoad

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];

[self.view addGestureRecognizer:tap];

在dismissKeyboard:

-(void)dismissKeyboard 
{
    [aTextField resignFirstResponder];
}

(其中,aTextField是负责键盘的文本字段)

Swift 3版本是这样的

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)

对于dismissKeyboard

@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
    aTextField.resignFirstResponder()
}