Reputation: 2499
I've been casting around looking for best-practices and whatnot for creating custom, reusable view components. So far, it seems like a custom UIView subclass is the way to go.
In this case, all I need is a fixed-size view with easy access to a label, and a convenience initializer would be great. I could tag the label and use a constant, but it seems unnecessary given this (boilerplate like UIKit importing removed) (with ARC):
// .h file
@interface MyView : UIView
@property (nonatomic, weak) IBOutlet UILabel *label;
+ (id)withText:(NSString *)text;
@end
// .m file
@implementation MyView
+ (id)withText:(NSString *)text {
MyView *view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
owner:nil
options:nil] objectAtIndex:0];
view.label.text = text;
return view;
}
@end
(edit: changed to class method. my concerns are still unchanged, though it's a bit less dubious overall)
My MyView.xib file's only top-level element (a UIView) has a custom class set to MyView, and the outlet is hooked up to the FileOwner.
And... this works. Perfectly. It renders correctly everywhere I'm using it, no exceptions, no clipping, no funny business at all that I can see.
So far. I'm more than a little concerned that:
Does someone with more UIView experience than I have mind lending their brain for a bit? Is this a good idea? A horrifying "omg wtf are you thinking" idea? Are there surprises waiting for me? Is there something I should read for how to create simple custom views like this?
Upvotes: 0
Views: 261
Reputation: 3657
In general, this technique should be fine. Since you're calling a class method as a "convenience initializer," self
refers to the class object and will not change, so it's fine to refer to it there. This is not anything like swizzling self in an initializer, which is trickier, but which can be done correctly.
In the case above, only the initWithCoder:
initializer will be called, as you're loading the view from a Nib.
Upvotes: 0
Reputation: 104065
You should read the Apple docs on initializers, and there’s also Mike Ash’s posts about them. Initializers are not hard, but there are some subtle issues that could bite you, as you could find out with your current code, as already mentioned in the comments.
Upvotes: 1