Loading custom UIView from nib, all subviews contained in nib are nil?

前端 未结 2 1790
一生所求
一生所求 2020-12-07 16:06

I have a custom UIView object with a nib that defines the view/subview layout. My outlets are connected, and when I init the object from ini

相关标签:
2条回答
  • 2020-12-07 16:14

    You may be misunderstanding how nib loading works. If you define a custom UIView and create a nib file to lay out its subviews you can't just add a UIView to another nib file, change the class name in IB to your custom class and expect the nib loading system to figure it out. You need to modify initWithCoder of your custom UIView class to programmatically load the nib that defines its subview layout. e.g.:

    - (id)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super initWithCoder:aDecoder]) {
            [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
            [self addSubview:self.toplevelSubView];
        }
        return self;
    }
    

    Your custom view's nib file needs to have the 'File's owner' class set to your custom view class and you need to have an outlet in your custom class called 'toplevelSubView' connected to a view in your custom view nib file that is acting as a container for all the subviews. Add additional outlets to your view class and connect up the subviews to 'File's owner' (your custom UIView).

    Alternatively, just create your custom view programmatically and bypass IB.

    0 讨论(0)
  • 2020-12-07 16:25

    Check that you are calling the 'super' implementation of initWithCoder: and awakeFromNib in each of your overridden methods i.e.

    - (id)initWithCoder:(NSCoder *)decoder {
        if ((self = [super initWithCoder:decoder])) {
          ...your init code...
        }
        return self;
    }
    
    - (void)awakeFromNib {
         [super awakeFromNib];
         ...your init code...
    }
    
    0 讨论(0)
提交回复
热议问题