点击返回Swift时如何让键盘关闭

时间:2016-02-15 15:50:30

标签: ios keyboard uitextfield swift2

请不要像我查看过其他帖子一样重复,因为我使用的是Swift 2< ---我认为这就是原因。

嗨,我有一个UITextField,当我点击它时,会像往常一样出现键盘。但是,当我点击返回键时没有任何反应。我尝试过使用:

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

    }

但这不起作用,因为当我点击返回时没有任何反应。我可以使用其他任何工作方式,还是我的代码中的错误。这是整个班级:

class SecondViewController: UIViewController, MFMailComposeViewControllerDelegate {



@IBOutlet var FullName: UITextField!
@IBOutlet var StartDate: UITextField!
@IBOutlet var EndDate: UITextField!
@IBOutlet var Room: UITextField!
@IBOutlet var Occupancy: UITextField!
@IBOutlet var Email: UITextField!
@IBOutlet var Number: UITextField!

func configuredMailComposeViewController() -> MFMailComposeViewController {
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property

    mailComposerVC.setToRecipients(["email@YourApp.com"])
    mailComposerVC.setSubject("App Feedback")
    mailComposerVC.setMessageBody("This is an automated email. \n  Hello, My name is \(FullName.text). \n I would like to book a room from  \(StartDate.text) to  \(EndDate.text). \n I would like the  \(Room.text) for \(Occupancy.text). \n You can Contact me at: \n  \(Email.text) and my phone number is: \(Number.text) \n Thank You", isHTML: false)

    return mailComposerVC
}

@IBAction func Send(sender: AnyObject) {
    let mailComposeViewController = configuredMailComposeViewController()

    if MFMailComposeViewController.canSendMail() {
        self.presentViewController(mailComposeViewController, animated: true, completion: nil)
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



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

    }



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

提前谢谢。

2 个答案:

答案 0 :(得分:0)

您必须实施UITextFieldDelegate协议 然后,您必须将ViewConrtoller设置为textFields的委托 请记住实现textFieldShouldReturn函数,该函数是按下返回按钮时调用的函数。您可以像这样实现它来关闭键盘:

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

答案 1 :(得分:0)

在viewdidload函数中写:

  

YOURTEXTFIELD.delegate = self

并且

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