(2015/6/30) CustomViewをCustomViewにaddSubviewしてる状態になってたので、こちらの記事を参考に修正しました。
CustomViewの作成
CustomView.h
# import <UIKit/UIKit.h>
@interface CustomView : UIView
@end
CustomView.m
# import "CustomView.h"
@interface CustomView ()
//xibのViewをこのプロパティに紐づける
@property (strong, nonatomic) IBOutlet UIView *contentView;
@end
@implementation CustomView
- (void)commonInit {
NSString* className = NSStringFromClass([self class]);
[[NSBundle bundleForClass:[self class]] loadNibNamed:className owner:self options:nil];
self.contentView.frame = self.bounds;
[self addSubview:self.contentView];
}
- (instancetype)init {
self = [super init];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
@end
xibの作成
CustomView.xib
という名前でxibを作成します。
xibがloadされてることを確かめやすいように、UILabelを一つ配置しときましょう。
xibのViewを, contentViewに紐づける
CustomView.xibでViewを選び、CustomView.mのcontentViewプロパティに接続しておきます。
xibのFile's OwnerをCustomViewに設定する
CustomView.xibでFile's Ownerを選び、IdentityInspectorでCustom ClassをCustomView
にします。
Storyboardへの配置
Main.storyboardで、ViewControllerにUIViewを貼っつけて、Custom ClassにCustomViewを設定します。
四辺にConstraintも設定しときましょう。
(見やすくするため、親viewを灰色にしてます)
動作確認
Runすると、ちゃんとLabelが貼りついていて、xibがロードされていることがわかります。