UIKit:以编程方式调用 awakeFromNib?

发布于 2024-11-16 14:57:22 字数 580 浏览 3 评论 0原文

我看到了这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野稚 2024-11-23 14:57:23

不,没有一种方法可以同时为代码中创建的对象和从 NIB 创建的对象调用。您应该编写一个包含公共初始化逻辑的单独方法,并从 awakeFromNibinitWithFrame: 调用它。

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 and initWithFrame:.

扶醉桌前 2024-11-23 14:57:23

每当 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 believe awakeFromNib 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 call awakeFromNib. Calling initWithFrame, 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 think initWithFrame is called regardless of whether your view is being created with a nib or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文