You do not want to create views inside the layoutSubviews
method. That method can be called multiple times and you'll create each view multiple times (having them overlap each other).
Instead create the views you need in the initWithFrame
method.
For the answer to your actual question, you probably need to set the frame of the new label to the bounds of the custom view. The bounds will have an origin of 0,0 and so it will work no mater where the custom view is placed in it's superview. If you use the frame, the label will be offset by however much the custom view is offset.
You can probably completely remove your layoutSubviews
method as that's not the place to set the label text either. Then add this:
- (instancetype)initWithFrame:(CGRect)frame withText:(NSString *)text
{
self = [super initWithFrame:frame];
if (!self) return nil;
self.backgroundColor = [UIColor grayColor];
self.layer.cornerRadius = 3;
self.layer.borderWidth = 1;
self.layer.borderColor = [UIColor blackColor].CGColor;
_text = text;
UILabel *label = [[UILabel alloc] initWithFrame:self.bounds];
label.text = @"";
if (![self.text isEqualToString:@"?"]) {
label.text = self.text;
label.textAlignment = NSTextAlignmentCenter;
}
[self addSubview:label];
return self;
}
If you want the label to resize when the custom view resizes, you could do that inside the layoutSubviews by setting the label.frame = self.bounds;
, but you'd be better off using autoresizing masks or auto layout.