2017-04-14 164 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值的打印后才显示。这就是为什么那里工作,并不适用于你的情况。