Swift:无法识别UITextField

时间:2017-04-14 22:33:00

标签: ios 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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-1)

我的猜测是,当你提出警报时,你当前的ViewController是警报viewController ......而在你的警报中,没有变量tField。

在示例中,您引用警报仅在使用tField值打印后显示。这就是为什么它在那里起作用而且在你的情况下不起作用。

相关问题