Peter
Peter

Reputation: 61

Where should I put UI Code in Swift?

So far I have used a storyboard to develop my UI. Now, I need to configure some UI-elements programmatically. For example rounded edges,..

I could put this UI code in viewDidLoad, but that can't be the right solution. Concerning the MVC concept, the controller has to be separated from the View.

So where should I put all the UI code? What are best practices?

Upvotes: 1

Views: 733

Answers (1)

Kiran
Kiran

Reputation: 687

Most of the times, you would put the UI code in the viewDidLayoutSubviews method, because it happens after AutoLayout has sorted the elements out and put arranged them properly on the view. For example, some code in viewDidLoad would not work right if you used constraints in Storyboard. ViewDidLoad runs before AutoLayout does its magic, so all of your height and width would be messed up if you used those values in the code.

viewDidLayoutSubviews runs after AutoLayout, so it's best to put it in there, unless you never use the frame values that could have been affected by AutoLayout. However, it's still good practice to put it in the viewDidLayoutSubviews. But just so you know, this method runs several times on certain actions, for example, just tapping on a UITextField would make it run again. This becomes a problem because it is bad for performance and may run unnecessary code. For example, you could want to add a special border underneath a text box. For this, you could create a new layer and add it to the text box using the height and width of it. Since it uses the frame properties, it would not work in viewDidLoad since the height and width have not been setup yet by AutoLayout. This means you would have to put it in viewDidLayoutSubviews, where it would keep getting called after tapping the textField, essentially adding an unlimited number of borders.

To fix this performance issue, it is actually best to create a subclass of your UI element and set things up in the override drawRect method. You can access all the properties of the object there, and it is easy to setup anything you want. Then in the storyboard Identity Inspector, change the class of the element to your subclass. This will allow Xcode to automatically do everything only when the element is created AND after AutoLayout is complete, making it the best way to customize the UI.

Finally, there is another way to customize elements. In the Identity Inspector, if you go to the User Defined Runtime Attributes, you can easily add properties and edit the values there. Just add a Key Path (the attribute name), then specify the type of value it is, and add it in! This is easy to do, but for some more complicated attributes, it is easier to just do it in code.

See the picture below to see where you can specify the subclass and add Runtime Attributes.

Customizing in Storyboard

Upvotes: 1

Related Questions