我已经整整几天了,真的可以使用一些帮助。
我有一个这样定义的属性:
@objcMembers class Account: Object {
dynamic var name = ""
当我向.name
加载文字时,即
let newAccount = Account()
// newAccount.name = self.accountTextField.text!
newAccount.name = "John Brown"
newAccount.isCurrent = true
newAccount.highWaterBalance = 0.0
我明白了:
acct.name is John Brown
acct.highWaterBalance is 0.0
acct.isCurrent is true
但是,当我在self.accountTextField
中键入“ John Brown”并使用以下代码时:
let newAccount = Account()
newAccount.name = self.accountTextField.text!
// newAccount.name = "John Brown"
newAccount.isCurrent = true
newAccount.highWaterBalance = 0.0
我明白了:
acct.name is
acct.highWaterBalance is 0.0
acct.isCurrent is true
我已经搜索了整个SO,并认为我对@rmaddy对this question的贡献有所了解。
我以为我做对了,但textField
还是一片空白。
任何帮助将不胜感激!
编辑1:
此代码:
print("Johnny B Goode\n")
print ("\(self.accountTextField.text!)")
print("Johnny B Bad\n")
打印此结果:
Johnny B Goode
Johnny B Bad
编辑2:
为清楚起见,也许我之前应该提到过,这是IBAction
代码,它生成self.accountTextField.text
所在的警报:
@IBAction func addAccountButton(_ sender: Any) {
// Pop alert to add new account
let addAcctAlert = UIAlertController(title: "Create New Account", message: "Please name your new account", preferredStyle: UIAlertControllerStyle.alert)
addAcctAlert.addTextField { (accountTextField) in
accountTextField.placeholder = "Enter new account name"
accountTextField.keyboardType = .`default`
}
addAcctAlert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.destructive, handler: { action in
// Create new Account with name, balance, isCurrent, save to disk
print("Johnny B Goode\n")
print ("\(self.accountTextField.text!)")
print("Johnny B Bad\n")
let newAccount = Account()
newAccount.name = self.accountTextField.text!
// newAccount.name = "John Brown"
newAccount.isCurrent = true
newAccount.highWaterBalance = 0.0
self.addCreatedAccount(thisAccount: newAccount)
}
))
addAcctAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(addAcctAlert, animated: true, completion: nil)
}
实际上,无论我在textField
中键入什么,它都不会产生任何结果。有可能吗?
答案 0 :(得分:0)
如果您试图从已添加到UIAlertController的帐号文本字段中获取值,那么您应该这样做。
newAccount.name = addAcctAlert.textFields?.first?.text ?? "I haven't typed anything in alert controller's text field"
或
if let accountName: String = addAcctAlert.textFields?.first?.text {
newAccount.name = accountName
}
答案 1 :(得分:0)
好吧,感谢@Rakesha Shastri,@ sinner和@MadProgrammer的慷慨指导,我在this question中得到了第二个答案,通过一些细微的调整,它为我提供了完美的服务!
非常感谢@Johnykutty和@Andrey Gordeev提供了简洁的解决方案!