问题
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?
回答1:
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:
.
回答2:
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.
来源:https://stackoverflow.com/questions/6446493/uikit-call-awakefromnib-programmatically