2014-10-10 93 views
4

當按下輸入按鈕時,我需要從我的警報視圖中的文本字段中獲取文本。Swift UIAlertController獲取文本字段文本

func inputMsg() { 

    var points = "" 
    var outOf = "" 

    var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert) 

    let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in 

     println("Cacle") 
    } 
    let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in 

     println("Input") 
     println(points) 
     println(outOf) 
    } 

    alertController.addAction(actionCancle) 
    alertController.addAction(actionInput) 
    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in 
     txtField.placeholder = "I got" 
     txtField.keyboardType = UIKeyboardType.NumberPad 
     points = txtField.text 
     }) 



    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in 
     txtField.placeholder = "Out Of" 
     txtField.keyboardType = UIKeyboardType.NumberPad 
     outOf = txtField.text 
    }) 
    presentViewController(alertController, animated: true, completion: nil) 
} 

回答

3

的UIAlertController有textFields屬性。這是它的文本字段。你的任何處理程序都可以檢查它,從而可以從任何文本字段獲取文本。

+0

我該怎麼做? – 2014-10-11 23:21:05

+0

你會怎麼做?我已經告訴過你需要知道的一切。警報控制器是'alertController'。其文本字段是「textFields」。他們的文本是他們的「文本」。你已經創建了一個輸入按鈕,並且你已經給它一個動作處理器,當按下輸入按鈕時它將運行,並且你已經把日誌消息放入它來證明它。它沒有比這更簡單。 – matt 2014-10-12 01:32:38

+0

@Unome不要用我沒有寫的代碼來破壞我的帖子。我_purposely_沒有提供代碼。如果你想用代碼添加你自己的答案,請隨時這樣做!這是完全合法的,並且比試圖混淆別人的答案要好得多。它對你有很多好處:你的答案可以得到提高; OP甚至可能會取消選中我的答案並檢查你的答案! – matt 2015-04-21 15:47:44

7

由於要求這裏是一個實施解決方案。

alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: { 
      (alert: UIAlertAction!) in 
      if let textField = alertController.textFields?.first as? UITextField{ 
       println(textField.text) 
      } 
     })) 

如上所述,alertController具有名爲textFields的屬性。如果您已添加文本字段,則可以有條件地解開該屬性以安全地訪問文本字段。在這種情況下,由於只有一個文本字段,我只是使用first屬性進行解包。希望能幫助到你。