【问题标题】:Implementing a custom view layout with Storyboard使用 Storyboard 实现自定义视图布局
【发布时间】:2014-05-07 14:31:39
【问题描述】:

我正在尝试为三个视图实现自定义布局。这些视图用于“酒吧”、“俱乐部”和“食物”类别。

每个类别都有自己的自定义圆形视图。在圆形视图中将是一个包含文本的标签。

当前设置
目前这三个视图被添加到 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 会更好吗?

【问题讨论】:

    标签: ios objective-c uiview uilabel


    【解决方案1】:

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

    在 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;
    }
    

    【讨论】:

    • 这对我不起作用,这一切都正确吗?注销标签框架时,我得到 0,0,注销框架文本时,我得到空值,但我已经一步一步地遵循了这一点。
    • self.text 实际设置在哪里?
    • 是的,self.text 并不是真正需要的,请更新您对self.mylabel.text = value; 的回答中的setValue 方法
    • 你是对的,你可以使用值:)。更新:)
    • 谢谢,在我们之间;)
    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 2015-04-01
    • 2016-01-21
    • 1970-01-01
    相关资源
    最近更新 更多