UIKit:以编程方式调用 awakeFromNib?
我看到了这段代码:
CoolButton *coolButton = [[CoolButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 25.0f)];
[coolButton awakeFromNib];
// ...
[coolButton release];
CoolButton
子类 UIButton
。可以以编程方式调用 awakeFromNib
吗?
如果我想要以编程方式而不是从 nib 文件创建对象,执行与 -[CoolButton awakeFromNib]
中相同的操作,那么最好的方法是什么?
我应该定义一个方法并在 -[CoolButton awakeFromNib]
和 -[CoolButton initWithFrame]
中调用它吗?或者,我是否应该定义另一种初始化方法,该方法在两种情况下都会被调用:无论是以编程方式还是从 nib 文件创建 CoolButton
?
I saw this code:
CoolButton *coolButton = [[CoolButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 60.0f, 25.0f)];
[coolButton awakeFromNib];
// ...
[coolButton release];
CoolButton
subclasses UIButton
. Is it OK to call awakeFromNib
programmatically?
What's the best way to do this if I want to do the same things that are done in -[CoolButton awakeFromNib]
for times that I want to create the object programmatically, instead of from a nib file?
Should I just define a method and call it in -[CoolButton awakeFromNib]
and -[CoolButton initWithFrame]
? Or, is there another initialization method I should define that gets called in both cases: whether I create a CoolButton
programmatically or from a nib file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有一种方法可以同时为代码中创建的对象和从 NIB 创建的对象调用。您应该编写一个包含公共初始化逻辑的单独方法,并从
awakeFromNib
和initWithFrame:
调用它。No, there isn't a method that gets called both for objects created in code and objects created from a NIB. You should write a separate method that contains the common initialization logic and call it from both
awakeFromNib
andinitWithFrame:
.每当 XIB 和 NIB 之间的所有连接都设置完毕时,
awakeFromNib
就会被调用。我相信当从 nib 文件初始化对象时,会在对象上调用awakeFromNib
。因此,如果您以编程方式创建它而不是使用 NIB 文件,则无需调用awakeFromNib
。另一方面,调用initWithFrame
听起来像是正确的方法。在此函数中,您可以通过编程方式创建视图,无需 nib 文件。我可能是错的,但我认为无论您的视图是否是使用笔尖创建的,都会调用initWithFrame
。Well
awakeFromNib
is called whenever all of the connections between the XIB and NIB are set. I believeawakeFromNib
is called on an object when it is initialized from a nib file. So if you are creating it programmatically and not with a NIB file, then there's no need to callawakeFromNib
. CallinginitWithFrame
, on the other hand, sounds like the way to go. In this function you can programmatically create your view, with no need for a nib file. I could be wrong, but I thinkinitWithFrame
is called regardless of whether your view is being created with a nib or not.