简体   繁体   中英

How to correctly load and show custom UIView in XIB?

Task is simple:

  1. We have a XIB.
  2. We have a custom UIView class implementation. Without XIB.
  3. We can add thanks to IB UIView element to the XIB and set its class to custom UIView class.
  4. We can create an outlet of our custom UIView class and connect custom UIView from XIB to it.
  5. But it seems that we should do additional steps to show our custom UIView (and its elements -- labels, images, etc) when XIB is loaded.
  6. Which steps?

UPD: The task is completed. We should use initWithCoder. Cite from Pizzaiola Gorgonzola : «initWithFrame is called when a UIView is created dynamically, from code. a view that is loaded from a .nib file is always instantiated using initWithCoder, the coder takes care of reading the settings from the .nib file». Thanks to question Subviews not showing up in UIView class .

如果这些元素不在nib / xib中,则可以在initWithCoder中添加/创建它们:

You may do something like this:

//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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM