使用inputAccessoryView关闭键盘

时间:2015-05-07 04:09:46

标签: objective-c swift

textview停靠在底部(就像消息应用程序一样)。但是,当用户点击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()
    }

2 个答案:

答案 0 :(得分: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()
    }

}

答案 1 :(得分:0)

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
   self.view.endEditing(true)
   return true
}