gpt4 book ai didi

swift - 从 UIAlertController 中的 UITextField 获取字符串 (Swift)

转载 作者:行者123 更新时间:2023-11-30 11:14:37 26 4
gpt4 key购买 nike

我这几天一直在抓狂,确实需要一些帮助。

我有一个如下定义的属性:

@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

我已经搜索了所有内容,并认为我已经解决了 @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 中输入什么内容,它都不会产生任何结果。这可能吗?

最佳答案

如果您尝试从添加到 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
}

关于swift - 从 UIAlertController 中的 UITextField 获取字符串 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51869322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com