我正在使用UITextfied,而点击textfied键盘出现,但当我按下返回键,键盘没有消失。我使用了以下代码:

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

方法resignfirstresponder没有进入函数。


当前回答

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
    self.view.addGestureRecognizer(tap)}

然后用这个函数

func handleScreenTap(sender: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

其他回答

所有在一个隐藏键盘和移动键盘打开视图:Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
    view.addGestureRecognizer(tap)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}


   override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
 @objc func taped(){
    
    self.view.endEditing(true)
    
}

@objc func KeyboardWillShow(sender: NSNotification){
    
    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
    }
    
    
}

@objc func KeyboardWillHide(sender : NSNotification){
    
    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y != 0{
        self.view.frame.origin.y += keyboardSize.height
    }
    
}


func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}
override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
    self.view.addGestureRecognizer(tap)}

然后用这个函数

func handleScreenTap(sender: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

你应该连接UITextfied和一个视图控制器的委托来调用这个函数

它的返回true部分只告诉文本字段是否允许返回。 你必须手动告诉文本字段解散键盘(或者它的第一个响应器是什么),这是通过resignFirstResponder()来完成的,如下所示:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

斯威夫特

使用UITextFieldDelegate的可选函数。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.endEditing(false)
}

False表示可以要求该字段辞职。真力辞职。