UIView
xib を使用してカスタムを作成しました。
さらに、UIViewController
ストーリーボードに があり、それに を追加してUIView
、そのクラスをカスタム に設定しましたUIView
。
しかし、アプリを実行しているとき、ビューにはサブビューがありません。デバッグすると、すべてのサブビューが null になります。
カスタムの .m にはUIView
、次の init メソッドが存在します。
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
}
return self;
}
何が足りないのでしょうか?
ベストアンサー1
すでにご存知のとおり、 にはxib に接続する方法UIViewController
があります。しかし...に関しては、 xib を使用してロードする必要があります。(-initWithNibName:bundle:
UIView
-loadNibNamed:owner:options:
xibのビューにカスタムクラスを指定するだけでは機能しません)
仮定する:
UIView
サブクラスを作成しましたCustomXIBView
- (新規ファイル > Cocoa Touch > Objective-C クラス -- サブクラス
UIView
)
- (新規ファイル > Cocoa Touch > Objective-C クラス -- サブクラス
- シンプルビューユーザーインターフェースを作成し、名前を付けました
CustomXIBView
- (新規ファイル > ユーザーインターフェイス > 表示)
手順:
CustomXIBView
のペン先へ- 選択する
View
(左ツールバー) - 選択する
Show Identity Inspector
(右側のパネルの3番目のオプション) - 指定
CustomXIBView
するカスタムクラスのView
- ペン先に
CustomXIBView
'sを付けないでくださいFile's Owner
- ペン先に
- オブジェクトをドラッグアンドドロップして接続します
CustomXIBView.h
コード:
//To load `CustomXIBView` from any `UIViewController` or other class:
//instead of the following commented code, do the uncommented code
//CustomXIBView *myCustomXIBViewObj = [CustomXIBView alloc] init];
//[myCustomXIBViewObj setFrame:CGRectMake(0,0,320,480)];
//Do this:
CustomXIBView *myCustomXIBViewObj =
[[[NSBundle mainBundle] loadNibNamed:@"someView"
owner:self
options:nil]
objectAtIndex:0];
[myCustomXIBViewObj setFrame:CGRect(0,
0,
myCustomXIBViewObj.frame.size.width,
myCustomXIBViewObj.frame.size.height)];
[self.view addSubview:myCustomXIBViewObj];