我想将自定义 View 的框架设置为我的 subview 的框架,它是一个 UILabel。但
当我使用 self.frame 时,UILabel
显示空文本。我需要在 CGRectMake
中对参数进行硬编码,以便查看我的 UILabel
。如何将 UILabel 的框架设置为自定义 View 的框架?
- (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];
}
最佳答案
layoutSubviews
会被多次调用,所以你不应该像这样addSubview
。更好的样式是设置 UILabel 的属性,例如 text
属性:
@property (nonatomic, strong) UILabel * label;
然后更改您的 layoutSubviews
代码:
- (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;
}
}
关于ios - 如何在自定义 View 中将 subview 的框架设置为其父框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21845019/