ViewのレイアウトはXIBファイルに書く。
ViewクラスのinitメソッドでXIBファイルを読み込む。
CustomView.m
- (id)init { NSArray *ary = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:nil options:nil]; if (ary && ary.count > 0){ self = [ary objectAtIndex:0]; } return self; }
ViewControllerのloadViewメソッドでviewプロパティをset
- (void)loadView { self.view = [[CustomView alloc] init]; }
このときに気をつけないといけないのが、XIBファイル上のUILabelとかからViewControllerにOutletを設定しないこと。
設定するとXIBファイルを読み込んだ時に以下のようなエラーメッセージが出る。
2012-08-27 17:35:08.759 THDoubleSlider[3752:f803] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x6aa25d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.'
代わりにCustomViewへのOutletを設定する。
ただし、ActionはViewControllerに設定しても大丈夫。