How can I use didSet to change the text of the UITextField (IBOutlet)?

I would like to set the text value of the UITextField (IBOutlet) to the DidSet of my model object that I am passing.

Here's the code:

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

      

And in the didSet of manageSettingViewController:

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

      

How do I set the text? Because in this case Xcode crashes because "keyTextField is zero" :(

+3


source to share


1 answer


You set manageSettingViewController.setting

right after instantiation manageSettingViewController

- at this point it hasn't loaded its view from nib / storyboard yet, so all its variables IBOutlet

(presumably keyTextField

and valueTextField

) are still zero. These text boxes are connected from the moment the method is called manageSettingViewController

viewDidLoad

.

You can change yours didSet

to test the optional outlets before configuring them, or assign via an additional chain:

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

      



This will avoid crashing, but it will also not be able to change the contents of the text box. You need to also implement viewDidLoad

for manageSettingViewController

to check its property setting

and set its text fields accordingly.

Of course, this will duplicate code from yours didSet

. This code can be helpful if you want to install setting

from a different location and update the UI automatically, but didSet

will not help you update the UI before loading the UI.

+2


source







All Articles