【问题标题】:How to hide keyboard when user taping return key用户点击返回键时如何隐藏键盘
【发布时间】:2015-06-17 04:03:33
【问题描述】:

我是一个 swift 程序员,我有 UIAlertViewController 有两个文本字段,我希望当用户点击 enter 时,键盘隐藏。但我不知道我应该做什么。这是我的代码

 var alert = UIAlertController(title: "خوش آمدید", message: "لطفا نام و نام خانوادگی خود را نام ببرید" , preferredStyle: UIAlertControllerStyle.Alert)
        var act = UIAlertAction(title: "تایید", style: UIAlertActionStyle.Destructive, handler: {(ACTION) in
            var name = alert.textFields![0] as! UITextField
            var lname = alert.textFields![1] as! UITextField
            self.namet = name.text
            self.lnamet = lname.text
            if (self.lnamet == "" && self.namet == "")
            {
            self.presentViewController(alert, animated: true, completion: nil)
            }
            self.defaults.setObject("done", forKey: "dn")
            var fulltext = " خوش اومدی " + self.namet + self.lnamet
            self.txt.text = fulltext
            var ntfc = UILocalNotification()
            ntfc.alertBody = "  برگرد  " + self.namet + "!"
            ntfc.fireDate = NSDate(timeIntervalSinceNow: 40)
            ntfc.soundName = "Untitled.m4a"
            UIApplication.sharedApplication().scheduleLocalNotification(ntfc)
        })
        alert.addTextFieldWithConfigurationHandler { (textField) -> Void in
            textField.placeholder = "نام"
            textField.clearButtonMode = UITextFieldViewMode.Always
        }



        alert.addTextFieldWithConfigurationHandler { (textField1) -> Void in
            textField1.placeholder = "نام خانوادگی"
            textField1.clearButtonMode = UITextFieldViewMode.Always
        }

【问题讨论】:

标签: ios swift


【解决方案1】:

首先在你的 ViewController 中实现这个UITextFieldDelegate
例如。

class MyViewController: UIViewController, UITextFieldDelegate {
....
}

现在向 TextField 添加一个委托,当您在下面的 viewDidLoad 方法或您正在初始化它的地方点击返回时,您希望在其中关闭键盘。
例如。

override func viewDidLoad() {

    super.viewDidLoad()
    myTextField.delegate = self
}

现在添加这个方法。

func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-23
    • 2011-03-30
    • 2014-12-26
    • 2013-09-17
    • 2011-05-13
    • 2016-06-14
    • 1970-01-01
    相关资源
    最近更新 更多