2014-10-02 59 views
2

我在遇到處理程序操作中的UIAlertController的textField時遇到問題,我想。我用google搜索了這個錯誤,但沒有得到太多的結果。我在Xcode 6.0.1中使用了Swift。這裏的錯誤:訪問UIAlertControllers textField

'[AnyObject]?' does not have a member named 'subscript'

@IBAction func addPressed(sender: UIBarButtonItem) { 
    var alert = UIAlertController(title: "New Event", message: "Name of the event?", preferredStyle: .ActionSheet) 
    alert.addTextFieldWithConfigurationHandler(){ 
     textField in 
     textField.placeholder = "Christmas" 
     textField.becomeFirstResponder() 
    } 
    alert.addAction(UIAlertAction(title: "Save", style: .Default, handler: { 
     action in 
     var text = alert.textFields[0].text // <-- cant access alert? The exclamation mark appears here 
    })) 

} 

使用((alert.textFields[0] as UITextField).text)使我有完全相同的錯誤。

回答

3

您只需解開UITextFields數組然後將其轉換爲UITextField,因爲它實際上是一個AnyObject數組。

下面是代碼應該是什麼樣子:

var text = (alert.textFields![0] as UITextField).text 
+1

非常感謝! :) – Linus 2014-10-02 06:53:25