ios - UITextField 键盘不解除

标签 ios swift uitextfield

我有一个 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/

相关文章:

ios - 更改整个应用程序的键盘外观

ios - 为什么我的 IBAction 会出现 "unrecognized selector"错误?

swift - 如何启用/禁用 TextField SWIFT

ios - 圆形背景上的 UIImageView,在 UICollectionViewCell 上

ios - 触摸外部时如何更改按钮字体?

xamarin - Mvvmcross:无法为绑定(bind) TextColor 创建目标绑定(bind)

ios5 - 调用 UITextField 委托(delegate)程序时 iPhone 模拟器崩溃(带有 EXC_BAD_ACCESS)

ios - 如何在 swift 中显示 CGPDFDocument?

ios - 如何在 plist 中保存持续时间?

ios - 快速编辑 UITableView 行项目