簡體   English   中英

Swift:UITextField無法識別

[英]Swift: UITextField is not being recognized

我希望用戶按下一個按鈕,然后讓他們能夠看到警報,在該警報中可以輸入輸入(以設置服務價格)。 另一個邏輯涉及將數據保存到數據庫中,這與我的問題並不真正相關。

我正在使用以下示例:

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
}

tFieldsetAmount函數內部的局部變量。 它不是該類的屬性。

更改:

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

我的猜測是,當您顯示警報時,當前的ViewController是警報viewController ...並且在警報中沒有變量tField。

在您引用的示例中,僅在打印了tField值之后才顯示警報。 那就是為什么在那行得通而對您而言不行的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM