简体   繁体   English

如何使用didSet更改UITextField(IBOutlet)的文本?

[英]How can I use didSet to change the text of a UITextField (IBOutlet)?

I'd like to set text value of UITextField (IBOutlet) in the DidSet of my model object that I pass. 我想在我传递的模型对象的DidSet中设置UITextField(IBOutlet)的文本值。

Here the code: 这里的代码:

    let manageSettingViewController: ManageSettingViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ManageSettingViewController") as ManageSettingViewController
    self.navigationController?.pushViewControllerCustom(manageSettingViewController)
    manageSettingViewController.setting = setting

And in the didSet of manageSettingViewController: 在manageSettingViewController的didSet中:

   var setting: Setting? {
    didSet
    {
        keyTextField.text = setting?.label
        valueTextField.text = setting?.value
    }

How can I set the text? 我该如何设置文字? Because in this case Xcode crash because "keyTextField is nil" :( 因为在这种情况下Xcode崩溃,因为“keyTextField是nil”:(

You're setting manageSettingViewController.setting right after instantiating manageSettingViewController -- at this point, it hasn't loaded its view from the nib/storyboard yet, so all of its IBOutlet variables (which presumably keyTextField and valueTextField are) are still nil. 您正在实例化manageSettingViewController之后设置manageSettingViewController.setting - 此时,它尚未从nib / storyboard加载其视图,因此它的所有IBOutlet变量(可能是keyTextFieldvalueTextField )仍然是零。 Those text fields are hooked up as of when ManageSettingViewController 's viewDidLoad method is called. 这些文本字段在调用ManageSettingViewControllerviewDidLoad方法时被连接起来。

You could change your didSet to check the optional outlets before setting them, or assign through optional chaining: 您可以在设置之前更改didSet以检查可选插座,或通过可选链接进行分配:

didSet {
    keyTextField?.text = setting?.label
    valueTextField?.text = setting?.value
}

This would avoid the crash, but it would also fail to change your text field's content. 这样可以避免崩溃,但也无法更改文本字段的内容。 You'd have to also implement viewDidLoad for ManageSettingViewController to check its setting property and set its text fields accordingly. 您还必须为ManageSettingViewController实现viewDidLoad以检查其setting属性并相应地设置其文本字段。

Of course, that would duplicate the code from your didSet . 当然,这会复制didSet的代码。 That code might still be useful if you want to set setting from elsewhere and have the UI update automatically, but didSet won't help you for updating UI before the UI loads. 如果您想从其他地方设置setting并自动更新UI,那么该代码可能仍然有用,但在加载UI之前, didSet将无法帮助您更新UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM