How is view initialized when loaded via a storyboard?

心不动则不痛 提交于 2019-11-28 16:35:35

问题


When view is loaded manually, developer remains in control when it comes to initializations, we choose what initializer to call, what variables to set etc.

When view is loaded from the storyboard segue ... what happens to that initializer? Where should variables be set i'd like to be available once view had been loaded?

Please help me understand the sequence here. How is instance of the class created here, who creates it and how can we intervene and help set it up to our liking?


回答1:


When a view is loaded from a nib or storyboard, it's -initWithCoder: method is called. Like -initWithFrame:, -initWithCoder: is a designated initializer for UIView. If you're going to do any custom initialization for a UIView subclass, you should make sure that it happens for both these methods. One common technique is to add a common initialization method that you call from both -initWithFrame: and -initWithCoder:. See my answer to Custom view and implementing init method? for a more detailed description.

Note that the documentation for -initWithFrame: explains:

If you use Interface Builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in a nib file are reconstituted and then initialized using their initWithCoder: method, which modifies the attributes of the view to match the attributes stored in the nib file.



来源:https://stackoverflow.com/questions/8373176/how-is-view-initialized-when-loaded-via-a-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!