gpt4 book ai didi

ios - 无法从其他类设置 UITextfield 的文本

转载 作者:行者123 更新时间:2023-11-28 10:09:20 24 4
gpt4 key购买 nike

我正在尝试使用以下代码为 FirstViewControllerSecondViewController 中的 UITextField 设置文本:

// First ViewController
@IBAction func buttonAction(_ sender: Any) {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
viewController?.sampleTxtField?.text = "world"
if let navigator = self.navigationController {
navigator.pushViewController(viewController!, animated: true)
}
}


// Second ViewController
@IBOutlet weak var sampleTxtField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
print("the textfield value is,\(String(describing: sampleTxtField?.text))")
}

在我得到的日志中:"the textfield value is,Optional("")"

我想我犯了一些愚蠢的错误。我检查了很多问题,但找不到任何解决方案。

最佳答案

您的代码有误。

let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
viewController?.sampleTxtField?.text = "world"

在上面的声明中, View 没有在 UI 中加载,所以 sampleTxtField 总是为 nil,而是在 SecondVC 中创建一个属性,var sample : String? 并将其分配为多于。然后在SecondVC的viewDidload中,赋值为textField.text = sample

// First ViewController

@IBAction func buttonAction(_ sender: Any) {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
viewController?.sample = "world"
if let navigator = self.navigationController {
navigator.pushViewController(viewController!, animated: true)
}
}

//第二个 View Controller

@IBOutlet weak var sampleTxtField: UITextField?
var sample : String?
override func viewDidLoad() {
super.viewDidLoad()
sampleTxtField.text = sample
print("the textfield value is,\(String(describing: sampleTxtField?.text))")
}

关于ios - 无法从其他类设置 UITextfield 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095623/

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