返回键操作点击警报

时间:2015-05-13 19:58:14

标签: ios swift

如何捕获返回键并按警报内的文本字段执行操作? 这是警报的代码:

    var alert = UIAlertController(title: "Add Country", message: "Add a country to the Speaker's List", preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Save", style: .Default) {
        (action: UIAlertAction!) -> Void in
        let textField = alert.textFields![0] as! UITextField
        self.countries.append(textField.text)
        self.speakersListTableView.reloadData()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .Default) {
        (action: UIAlertAction!) -> Void in
    }

    alert.addTextFieldWithConfigurationHandler {
        (textField: UITextField!) -> Void in
    }

    alert.addAction(saveAction)
    alert.addAction(cancelAction)

1 个答案:

答案 0 :(得分:0)

您需要设置文本字段的委托并在您的类中实现UITextFieldDelegate。像这样:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate
{
    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 viewDidAppear(animated: Bool)
    {
        var alert = UIAlertController(title: "Add Country", message: "Add a country to the Speaker's List", preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save", style: .Default) {
            (action: UIAlertAction!) -> Void in
            let textField = alert.textFields![0] as! UITextField
            //self.countries.append(textField.text)
            //self.speakersListTableView.reloadData()
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .Default) {
            (action: UIAlertAction!) -> Void in
        }

        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField!) -> Void in
            textField.delegate = self
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        self.presentViewController(alert, animated: true) { () -> Void in
        }
    }


    func textFieldDidBeginEditing(textField: UITextField)
    {
        println("textFieldDidBeginEditing")
    }

    func textFieldDidEndEditing(textField: UITextField) {
        println("textFieldDidEndEditing")
    }

}