Subviews not showing up in UIView class

2019-08-31 02:15发布

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];
}

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-31 03:07

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)

查看更多
不美不萌又怎样
3楼-- · 2019-08-31 03:10

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

查看更多
登录 后发表回答