簡體   English   中英

在界面構建器中添加的自定義UIView不會加載xib

[英]Custom UIView added in the interface builder does not load the xib

我用xib創建了自定義UIView

另外我在我的故事板中有一個UIViewController ,我已經添加了一個UIView並將其類設置為我的自定義UIView

但是當我運行應用程序時,視圖沒有其子視圖。 調試時,所有子視圖都為null。

在自定義UIView .m中,存在以下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;
}

我錯過了什么?

如您所知,使用UIViewController我們使用-initWithNibName:bundle:方法將其與xib連接。
但...
說到UIView ,你需要使用-loadNibNamed:owner:options:並用xib加載它。 只是在xib中為視圖指定自定義類將不起作用


假設:

  1. 創建了一個名為CustomXIBViewUIView子類
    • 新文件> Cocoa Touch> Objective-C類 - UIView子類
  2. 創建了一個簡單的視圖用戶界面並將其命名為CustomXIBView
    • 新文件>用戶界面>查看

腳步:

  1. 轉到CustomXIBView的筆尖
  2. 選擇View左側工具欄
  3. 選擇Show Identity Inspector右側面板中的第3個選項
  4. CustomXIBView指定為View自定義類
    • 不要在筆尖中使用CustomXIBViewFile'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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM