インターフェースビルダーに追加されたカスタムUIViewはxibをロードしません質問する

インターフェースビルダーに追加されたカスタムUIViewはxibをロードしません質問する

UIViewxib を使用してカスタムを作成しました。

さらに、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のビューにカスタムクラスを指定するだけでは機能しません


仮定する:

  1. UIViewサブクラスを作成しましたCustomXIBView
    • 新規ファイル > Cocoa Touch > Objective-C クラス -- サブクラスUIView
  2. シンプルビューユーザーインターフェースを作成し、名前を付けましたCustomXIBView
    • 新規ファイル > ユーザーインターフェイス > 表示

手順:

  1. CustomXIBViewのペン先へ
  2. 選択するView左ツールバー
  3. 選択するShow Identity Inspector右側のパネルの3番目のオプション
  4. 指定CustomXIBViewするカスタムクラスView
    • ペン先にCustomXIBView'sを付けないでくださいFile's Owner
  5. オブジェクトをドラッグアンドドロップして接続します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];

参照:http://eppz.eu/blog/uiview-from-xib/

おすすめ記事