通过故事板加载时如何初始化视图? [英] How is view initialized when loaded via a storyboard?

查看:85
本文介绍了通过故事板加载时如何初始化视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当手动加载视图时,开发人员在初始化时仍然处于控制之中,我们选择要调用的初始化程序,要设置的变量等。

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.

当视图是从故事板中加载segue ...初始化程序会发生什么?应该在哪里设置变量我希望在加载视图后可以使用?

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?

推荐答案

从nib或storyboard加载视图时,会调用 -initWithCoder:方法。像 -initWithFrame: -initWithCoder:是UIView的指定初始值设定项。如果您要为UIView子类进行任何自定义初始化,则应确保这两种方法都发生了这种情况。一种常见的技术是添加一个通用的初始化方法,您可以从 -initWithFrame: -initWithCoder:中调用它。请参阅我的回答自定义视图并实现init方法?以获得更详细的描述。

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.

请注意 -initWithFrame的文档:解释:


如果使用Interface Builder设计界面,则当您的视图对象随后被调用时,此方法为
从nib
文件加载。重构nib文件中的对象,然后使用其initWithCoder:方法初始化
,该方法修改视图的
属性以匹配存储在nib文件中的属性。

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.

这篇关于通过故事板加载时如何初始化视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆