Chris Hulbert - splinter.com.au
Objective-C
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface MyCustomView : UIView
@end
Run time, manual | Run time, xib | Design time |
---|---|---|
initWithFrame | initWithCoder | initWithFrame |
awakeFromNib | KVC | |
prepareForInterfaceBuilder | ||
That's right folks, IBDesignable doesn't use NSCoding
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
#if !TARGET_INTERFACE_BUILDER
[self commonInit]; // Run time, manual creation.
#endif
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self commonInit]; // Run time, loading from xib.
}
- (void)prepareForInterfaceBuilder {
[super prepareForInterfaceBuilder];
[self commonInit]; // Design time.
}
Why not call from initWithFrame? 2 birds with one stone: manual run time + design time.
KVC of IB properties occurs after initWithFrame, so your settings eg backgroundColor would be clobbered.
@implementation MyCustomView {
UILabel *_label;
}
- (void)commonInit {
_label = [[UILabel alloc] init];
_label.text = @"TEST";
[self addSubview:_label];
}
- (void)layoutSubviews {
[super layoutSubviews];
_label.frame = self.bounds;
}
@end
[UIImage imageNamed:] won't work, as it runs from a framework, no bundle context. Instead:
[UIImage imageNamed:@"MyImage"
inBundle:[NSBundle bundleForClass:[self class]]
compatibleWithTraitCollection:nil];
So please remember:
Chris Hulbert - splinter.com.au