Subviews not showing up in UIView class

2019-08-31 02:54发布

问题:

I'm trying to lay out some images in code using addSubview, and they are not showing up.

I created a class (myUIView) that subclasses UIView, and then changed the class of the nib file in IB to be myUIView.

Then I put in the following code, but am still getting a blank grey screen.

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews
{
    self.backgroundColor = [UIColor blackColor];

    UIImageView *black = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"black.png"]];
    black.center = self.center;
    black.opaque = YES;

    [self addSubview:black];

    [black release];
}

回答1:

yes, just implement initWithCoder.

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

i took the habit to do the initialization in a separate method, implementing both initWithCode and initWithFrame (and my own initialization methods when required)



回答2:

try implementing initWithCoder: sometimes I've had trouble with IB and initWithFrame:

or at least add a logging call to see if your init method is executed