ios 通过故事板加载时如何初始化视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8373176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:44:21  来源:igfitidea点击:

How is view initialized when loaded via a storyboard?

objective-ciosxcode4.2storyboard

提问by James Raitsev

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?

当视图从故事板 segue 加载时......那个初始化器会发生什么?加载视图后,应该在哪里设置变量?

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?

请帮我理解这里的顺序。类的实例是如何在这里创建的,是谁创建的,我们如何干预并帮助按照我们的喜好设置它?

回答by Caleb

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 answerto Custom view and implementing init method?for a more detailed description.

当从笔尖或故事板加载视图时,它的-initWithCoder:方法被调用。Like -initWithFrame:,-initWithCoder:是 UIView 的指定初始值设定项。如果您要为 UIView 子类进行任何自定义初始化,则应确保这两种方法都进行了初始化。一种常见的技术是添加一个从-initWithFrame:和调用的公共初始化方法-initWithCoder:。请参阅自定义视图和实现 init 方法的回答以获得更详细的描述。

Note that the documentation for -initWithFrame:explains:

请注意,文档-initWithFrame:解释了:

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.

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