尝试使用“返回”按钮关闭键盘

时间:2015-07-13 21:58:48

标签: ios swift

我正在构建一个待办事项列表应用程序,我想这样做当用户按下“返回”时键入键盘将关闭并消失。我以为我正确地写了这个函数,但它不起作用。我到底要问的一点代码。

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet var addLabel: UILabel!


    @IBOutlet var enteredItem: UITextField!


    @IBAction func addItemButton(sender: AnyObject) {

        toDoList.append(enteredItem.text)

        enteredItem.text = ""

        NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList")

    }


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

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

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        self.view.endEditing(true)

    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {

        textField.resignFirstResponder()

        return true

    }

}

1 个答案:

答案 0 :(得分:0)

你错过了两件事

  • SecondViewController必须实现UITextFieldDelegate
class SecondViewController: UIViewController, UITextFieldDelegate
  • 您必须将文字字段委托设置为self
override func viewDidLoad() {
   super.viewDidLoad()
   self.enteredItem.delegate = self;
}