使用Storyboard实现自定义视图布局

时间:2014-05-07 14:31:40

标签: ios objective-c uiview uilabel

我正在尝试为三个视图实现自定义布局。这些视图用于" Bars"," Clubs"和"食物"。

每个类别都有自己的自定义圈子视图。在圆圈视图中将是一个标签,其中包含文字。

当前设置
目前,三个视图被添加到Storyboard,并给出了相关的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会更好吗?

1 个答案:

答案 0 :(得分:1)

您可以在自定义UIView中创建名为text的属性,然后使用User Runtime Attributes进行更改。

在Interface Builder中,您可以:

enter image description here

然后您可以在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;
}