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


当前回答

在我的新发展中,我以巴里为例。它工作得很好!但我不得不包括一个轻微的变化,要求解散键盘,只有文本字段被编辑。

所以,我在Barry的例子中加入了以下内容:

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    _textBeingEdited = textField;
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
    _textBeingEdited = nil;
}

同时,我修改了hideKeyboard方法如下:

- (IBAction)hideKeyboard:(id)sender
{
    // Just call resignFirstResponder on all UITextFields and UITextViews in this VC
    // Why? Because it works and checking which one was last active gets messy.
    //UITextField * tf = (UITextField *) sender;
    [_textBeingEdited resignFirstResponder];
}

其他回答

在这种情况下,可以使用ScrollView,并添加到文本字段在ScrollView和我想点击ScrollView和视图,然后解散键盘。为了以防万一,我尝试创建了示例代码。像这样,

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
        view.addGestureRecognizer(tapGesture)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

你的故事板看,就像。

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

试试这个;

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; }

在viewDidLoad 斯威夫特4.2 代码是这样的

let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
        view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
        view.endEditing(true)
    }

如果视图被嵌入到UIScrollView中,那么你可以使用以下方法:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

前者会在表格视图滚动时将键盘动画化,后者会像股票消息应用程序一样隐藏键盘。

注意,这些都可以在iOS 7.0或更高版本上使用。

发送消息resignFirstResponder的文本文件,把它放在那里。请参阅这篇文章了解更多信息。