2017-04-14 171 views
0

我希望用戶按下一個按鈕,然後讓他們能夠在可以輸入輸入(爲服務設置價格)的地方看到警報。另一個邏輯涉及將數據保存到數據庫中,這與我的問題無關。Swift:UITextField未被識別

我用下面的例子:

https://stackoverflow.com/a/30139623/2411290

它肯定的作品,因爲它正確地顯示警報,但一旦我有

print("Amount: \(self.tField.text)") 

「self.tField.text」不被認可。特定的錯誤我得到的是:類型的

值 'testVC' 沒有成員 'tField'

@IBAction func setAmount(_ sender: Any) { 

    var tField: UITextField! 


    func configurationTextField(textField: UITextField!) 
    { 
     print("generating textField") 
     textField.placeholder = "Enter amount" 
     tField = textField 

    } 

    func handleCancel(alertView: UIAlertAction!) 
    { 
     print("Cancelled") 
    } 

    let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert) 

    alert.addTextField(configurationHandler: configurationTextField) 
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:handleCancel)) 
    alert.addAction(UIAlertAction(title: "Done", style: .default, handler:{ (UIAlertAction) in 
     print("Done !!") 

    })) 
    self.present(alert, animated: true, completion: { 
     print("completion block") 
     print("Amount: \(self.tField.text)") // Error here 


    }) 

    //// other logic for app 
} 

回答

2

tField是你setAmount函數中的局部變量。這不是班級的財產。

變化:

self.tField.text 

到:

tField.text 

,將允許您訪問本地變量。

但真正的問題是你爲什麼要在這個函數內部創建一個局部變量UITextField?當文本字段在任何地方都沒有使用時,爲什麼要打印它的文本?

很可能您應該訪問「完成」按鈕的操作處理程序內的警報文本字段。在呈現警報的完成塊內不需要做任何事情。

@IBAction func setAmount(_ sender: Any) { 
    let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert) 

    alert.addTextField(configurationHandler: { (textField) in 
     print("generating textField") 
     textField.placeholder = "Enter amount" 
    }) 

    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action) in 
     print("Cancelled") 
    }) 

    alert.addAction(UIAlertAction(title: "Done", style: .default) { (action) in 
     print("Done !!") 
     if let textField = alert.textFields?.first { 
      print("Amount: \(textField.text)") 
     } 
    }) 

    self.present(alert, animated: true, completion: nil) 
} 
+0

我真的很感謝幫助,所以謝謝。我創建了幾個全局變量,price和tField(UITextField)。我無法真正處理「完成」處理程序中的所有邏輯,因此我需要存儲價格的值,因爲我一次向警報外的Firebase數據庫輸入了5-6個值。 – user2411290

+0

沒有必要將文本字段存儲爲全局變量。 – rmaddy

+0

我正在添加self.price = self.tField.text!在我的「完成」處理程序中。當我嘗試將它保存到我的數據庫(在警報之後)時,它似乎並不像它保存價值。我猜這不是正確的方式去做這件事。讓我試試你的確切實現。 – user2411290

-1

我的猜測是,當你提出警報時,你當前的ViewController是alert alertler ...並且在你的alert中沒有變量tField。

在您引用的exampled上,警報僅在具有tField值的打印後才顯示。這就是爲什麼那裏工作,並不適用於你的情況。