我正在尝试为三个视图实现自定义布局。该视图用于“酒吧”,“俱乐部”和“食物”的类别。
这些类别中的每一个都有自己的自定义圈子视图。在圆形视图内将是一个包含文本的标签。
当前设置
目前,这三个视图已添加到情节提要中,并提供了相关的UIView
子类。然后,子类处理使它们循环并添加标签。
- (id)init {
self = [super init];
if (self) {
[self setupView];
}
return self; }
-(void)setupView {
self.translatesAutoresizingMaskIntoConstraints = NO;
float newRadius = self.frame.size.width/2;
self.layer.cornerRadius = newRadius; // TODO / TEST - The UIImageView is set to 40x40 and the frame is yet to be created
self.layer.masksToBounds= YES;
self.layer.borderWidth = 5;
self.layer.borderColor = [UIColor colorWithRed:0.138 green:0.225 blue:1.000 alpha:1.000].CGColor;
self.backgroundColor = [self randomColor];
[self setupLabel];
}
-(void)setupLabel {
UILabel *label = [[UILabel alloc]init];
label.translatesAutoresizingMaskIntoConstraints = NO;
label.text = @"Test";
label.textColor = [UIColor whiteColor];
label.text = [label.text uppercaseString];
[self addSubview:label];
[self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
}
但是,使用上述设置,我无法想到如何用不同的标签文本实现每个圆形视图?
什么是处理此自定义视图和布局的最佳方法。最好用代码完全创建圆视图,然后更改自定义init方法以将NSString传递给标签,这会更好吗?
您可以在自定义UIView中创建一个名为text的属性,然后使用“用户运行时属性”对其进行更改。
在Interface Builder中,您可以:
然后,您可以在CustomView中覆盖:
// This method will get called for each attribute you define.
-(void) setValue:(id)value forKey:(NSString *)key {
if ([key isEqualToString:@"text"]) {
self.mylabel.text = value;
}
}
请注意,您需要在属性中添加标签。@property (nonatomic, weak) UILabel* myLabel
因此,设置标签时,您需要:
-(void)setupLabel {
UILabel *label = [[UILabel alloc]init];
//...
[self addSubview:label];
//the label, since it is weak, needs to be added to the visual tree first
self.myLabel = label;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句