簡體   English   中英

如何在XIB中正確加載和顯示自定義UIView?

[英]How to correctly load and show custom UIView in XIB?

任務很簡單:

  1. 我們有XIB。
  2. 我們有一個自定義的UIView類實現。 沒有XIB。
  3. 我們可以向XIB添加IB UIView元素,並將其類設置為自定義UIView類。
  4. 我們可以創建自定義UIView類的出口,並將自定義UIView從XIB連接到它。
  5. 但是看來,當加載XIB時,我們應該做一些額外的步驟來顯示我們的自定義UIView(及其元素-標簽,圖像等)。
  6. 哪個步驟?

UPD:任務已完成。 我們應該使用initWithCoder。 Pizzaiola Gorgonzola引用:«initWithFrame是通過代碼動態創建UIView時調用的。 從.nib文件加載的視圖始終使用initWithCoder實例化,編碼器負責從.nib文件中讀取設置»。 多虧了問題Subviews沒有出現在UIView類中

如果這些元素不在nib / xib中,則可以在initWithCoder中添加/創建它們:

您可以執行以下操作:

//MYCustomView.h
@interface MYCustomView : UIView
@end

//MYCustomView.m
@implementation MYCustomView

- (void)setup {
    // Do custom stuffs here...
}

- (id)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

@end

暫無
暫無

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

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