newguy newguy - 2 months ago 5
Objective-C Question

How to set a subview's frame to be its parent's frame in a custom view

I want to set the custom view's frame as my subview's frame, which is a UILabel. but
when I use self.frame the

UILabel
shows empty text. I need to hardcode the parameters in
CGRectMake
in order to see my
UILabel
. How do I set the UILabel's frame to be my custom view's frame?

- (id)initWithFrame:(CGRect)frame withText:(NSString *)text
{
self = [super initWithFrame:frame];

if (self) {
self.backgroundColor = [UIColor grayColor];
self.layer.cornerRadius = 3;
self.layer.borderWidth = 1;
self.layer.borderColor = [UIColor blackColor].CGColor;
_text = text;
}

return self;
}

- (void)layoutSubviews
{
// This works
// UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
// This doesn't work
UILabel *label = [[UILabel alloc] initWithFrame:self.frame];
label.text = @"";
if (![self.text isEqualToString:@"?"]) {
label.text = self.text;
label.textAlignment = NSTextAlignmentCenter;
}

[self addSubview:label];
}

Answer

layoutSubviews will be invoked many times, so you should not addSubview like this. Better style is to set a property of UILabel, like your text property:

@property (nonatomic, strong) UILabel * label;

then change your layoutSubviews code:

- (void)layoutSubviews
{
    if(!self.label){
         self.label = [[UILabel alloc] initWithFrame:self.frame]; //Use ARC
         self.label.textAlignment = NSTextAlignmentCenter;
         [self addSubview:self.label];
    }

    self.label.frame = self.bounds;
    if (![self.text isEqualToString:@"?"]) {
        self.label.text = self.text;
    }
}
Comments