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


当前回答

有一件事很重要……

添加手势识别到视图可以覆盖它的子视图。 所以只执行一个动作。 如果你想通过父视图和子视图执行多重识别操作… 你必须使用

 tap.cancelsTouchesInView = false

完整代码如下:

 let tap = UITapGestureRecognizer(target: self, action: #selector(self.superViewClicked))
        tap.numberOfTapsRequired = 1
        tap.delegate = self
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)




  @objc func superViewClicked(){
        
        self.searchTF.resignFirstResponder()
    }

在外面点击关闭软键盘的最佳解决方案是什么?

我将解释一个条件:

想想看:你在顶部有UISearchBar, 然后添加头表视图!

解决方法很简单:

跟踪软键盘打开或关闭 添加手势识别头视图 实现表视图didSelectRowAt的委托

完整的代码:

   var isSoftKeyboardActive = false

    override func viewDidLoad() {
    
    
        var tap = UITapGestureRecognizer(target: self, action: #selector(self.tableHeaderClick))
            tap.numberOfTapsRequired = 1
            tap.delegate = self
            tap.cancelsTouchesInView = false
            self.headerOfTableView.addGestureRecognizer(tap)
    
    }
    
          override func viewWillAppear(_ animated: Bool) {
                  super.viewWillAppear(animated)
                 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
                  NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil)
              }
              
              override func viewWillDisappear(_ animated: Bool) {
                  super.viewWillDisappear(animated)
                  NotificationCenter.default.removeObserver(self)
              }
        


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          if isSoftKeyboardActive == true{
               
               self.searchTF.resignFirstResponder()
           }else{
           
               selectedRow = indexPath.row
               performSegue(withIdentifier: "segueWebview", sender: self)
               
           }
    }
    


 
    @objc func tableHeaderClick(){
         
        self.searchTF.resignFirstResponder()
    
     }
    
    
    
  @objc func keyboardWillAppear() {

        
        isSoftKeyboardActive = true
    }

    @objc func keyboardWillDisappear() {
        
        isSoftKeyboardActive = false
        
    }
 

它是如何工作的:

如果软键盘是打开的,用户点击头软键盘关闭 如果软键盘打开,用户点击单元格,键盘关闭,不执行单元格点击

其他回答

@Jensen2k回答的Swift版本:

let gestureRecognizer : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: "dismissKeyboard")
self.view.addGestureRecognizer(gestureRecognizer)

func dismissKeyboard() {
    aTextField.resignFirstResponder()
}

一个衬套

self.view.addTapGesture(UITapGestureRecognizer.init(target: self, action: "endEditing:"))

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

所以,我在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];
}

斯威夫特4

用这个扩展方法设置你的UIViewController,例如在viewDidLoad中:

override func viewDidLoad() {
    super.viewDidLoad()
    self.setupHideKeyboardOnTap()
}

即使点击导航栏,键盘也会被取消。

import UIKit
extension UIViewController {
    /// Call this once to dismiss open keyboards by tapping anywhere in the view controller
    func setupHideKeyboardOnTap() {
        self.view.addGestureRecognizer(self.endEditingRecognizer())
        self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
    }

    /// Dismisses the keyboard from self.view
    private func endEditingRecognizer() -> UIGestureRecognizer {
        let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
        tap.cancelsTouchesInView = false
        return tap
    }
}

我试了这里的很多回答,都不太走运。我的点击手势识别器总是导致我的UIButtons在点击时不响应,即使我将手势识别器的cancelsTouchesInView属性设置为NO。

这就是最终解决问题的方法:

有一个ivar:

UITapGestureRecognizer *_keyboardDismissGestureRecognizer;

当文本字段开始编辑时,设置手势识别器:

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    if(_keyboardDismissGestureRecognizer == nil)
    {
        _keyboardDismissGestureRecognizer = [[[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(dismissKeyboard)] autorelease];
        _keyboardDismissGestureRecognizer.cancelsTouchesInView = NO;

        [self.view addGestureRecognizer:_keyboardDismissGestureRecognizer];
    }
}

窍门在于如何设置遣散键盘方法:

- (void) dismissKeyboard
{
    [self performSelector:@selector(dismissKeyboardSelector) withObject:nil afterDelay:0.01];
}

- (void) dismissKeyboardSelector
{
    [self.view endEditing:YES];

    [self.view removeGestureRecognizer:_keyboardDismissGestureRecognizer];
    _keyboardDismissGestureRecognizer = nil;
}

我猜有一些关于从触摸处理执行堆栈中获得dismissKeyboardSelector执行的东西…

最简单和最短的方法之一是将此代码添加到viewDidLoad

[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]
                                     initWithTarget:self.view
                                     action:@selector(endEditing:)]];