gpt4 book ai didi

ios - UITextField 键盘不解除

转载 作者:搜寻专家 更新时间:2023-11-01 06:46:38 24 4
gpt4 key购买 nike

我有一个 UIViewController,里面有一个 UITextField,当我点击离开或关闭 View 时,我试图关闭键盘。然而,当我调用 resignFirstResponder() 时,键盘仍然没有关闭,我不太清楚为什么。这是我的代码:

class MessageViewController: UIViewController, UITextFieldDelegate {
var messageTextField : UITextField = UITextField()

override func viewDidLoad() {
...
messageTextField.frame = CGRectMake(10, UIScreen.mainScreen().bounds.size.height-50, UIScreen.mainScreen().bounds.size.width-80, 40)
messageTextField.delegate = self
messageTextField.borderStyle = UITextBorderStyle.Line
messageTextField.becomeFirstResponder()
self.view.addSubview(messageTextField)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
...
}

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

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
println("Touched")
}

func keyboardWillShow(notification: NSNotification) {
var keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey]as? NSValue)?.CGRectValue()
let messageFrame = messageTextField.frame
let newY = messageFrame.origin.y - keyboardSize!.height
messageTextField.frame = CGRectMake(messageFrame.origin.x, newY, messageFrame.size.width, messageFrame.size.height)
}

func keyboardWillHide(notification: NSNotification) {
var keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey]as? NSValue)?.CGRectValue()
let messageFrame = messageTextField.frame
let newY = messageFrame.origin.y - keyboardSize!.height
messageTextField.frame = CGRectMake(messageFrame.origin.x, newY, messageFrame.size.width, messageFrame.size.height)
}

}

有谁知道为什么键盘没有消失?我以编程方式将 UITextField 添加到 View 中,而不是使用 Storyboard。这有什么不同吗?

最佳答案

 class ViewController: UIViewController,UITextFieldDelegate {

确认协议(protocol)

messageTextField.delegate=self

设置委托(delegate)

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

使用此代码..

关于ios - UITextField 键盘不解除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29936137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com