【问题标题】:Dismiss Keyboard with inputAccessoryView使用 inputAccessoryView 关闭键盘
【发布时间】:2015-05-07 04:09:46
【问题描述】:

文本视图停靠在底部(如消息应用程序)。但是,当用户在 textView 之外点击时,键盘不会关闭。

import UIKit
class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var commentBar: UIView!

    @IBOutlet var commentTextField: UITextField!

    override var inputAccessoryView: UIView {
        return commentBar
    }

    override func canBecomeFirstResponder() -> Bool {
        commentBar.removeFromSuperview()
        return true
    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
        self.view.endEditing(true);
        return false;
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true);
        commentTextField.resignFirstResponder()
    }

【问题讨论】:

  • 检查您的视图是否启用了用户交互。
  • @BrittoThomas 是的,用户交互已启用

标签: objective-c swift


【解决方案1】:

无需在 canBecomeFirstResponder 方法中删除您的 commentBar。这将在每次键盘退出时调用。

试试这样的。

class ViewController: UIViewController {
@IBOutlet var commentBar: UIView!
@IBOutlet var commentTextField: UITextField!

override func viewDidLoad() {
       super.viewDidLoad()
       commentBar.removeFromSuperview()
    }
override var inputAccessoryView: UIView {
       return commentBar
    }

override func canBecomeFirstResponder() -> Bool {
       return true
    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
       self.view.endEditing(true);
       return false;
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
      self.view.endEditing(true);
      commentTextField.resignFirstResponder()
    }

}

【讨论】:

  • 谢谢,我试了一下,但它仍然没有关闭键盘。此外,如果我呈现另一个视图控制器(如登录)并返回,commentBar 将完全消失。
  • 检查func touchesBegan是否在调用,使用断点。
  • 还要检查 textField 到 IBOutlet 的连接。
  • 是的,textField是连接的@IBOutlet var commentTextField: UITextField!而且我用了断点,发现touchesBegan从来没有被调用过。
【解决方案2】:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   self.view.endEditing(true)
   return true
}

【讨论】:

  • 你应该对你的答案做一些解释
猜你喜欢
  • 1970-01-01
  • 2012-06-01
  • 2015-04-14
  • 2018-06-11
  • 2012-09-16
  • 1970-01-01
  • 2014-12-23
  • 2017-06-25
  • 2011-04-20
相关资源
最近更新 更多