2015-05-13 59 views
1

如何捕獲回車鍵並對警報內的文本字段執行操作? 下面是警報代碼:您需要設置文本字段的委託,並在你的類實現UITextFieldDelegate按回車鍵操作在警報中輸入

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) 

回答

0

。像這樣:

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") 
    } 

} 
+0

謝謝!如何讓textFieldDidEndEditing函數關閉在viewDidAppear中打開的警報? –

+0

此外,我希望textFieldDidEndEditing函數可以執行與saveAction函數相同的操作,但是當Save操作被觸發時,我不會完成雙倍的工作。有什麼建議麼?再次感謝! –

+0

看看這個問題的答案,我認爲這是你在找什麼:http://stackoverflow.com/a/25628065/341994 –