Subviews not showing up in UIView class

风流意气都作罢 提交于 2019-12-11 16:12:27

问题


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



来源:https://stackoverflow.com/questions/753813/subviews-not-showing-up-in-uiview-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!