ios - 使用 Storyboard 实现自定义 View 布局

标签 ios objective-c uiview uilabel

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

每个类别都有自己的自定义圈 subview 。在圆 View 内将是一个包含文本的标签。

当前设置
目前这三个view都添加到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]];
}

但是,通过上述设置,我想不出如何使用不同的标签文本实现每个圆 View ?

处理此自定义 View 和布局的最佳方式是什么。完全在代码中创建圆 View 并更改自定义 init 方法以改为为标签传递 NSString 会更好吗?

最佳答案

您可以在自定义 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(非原子,弱)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;
}

关于ios - 使用 Storyboard 实现自定义 View 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23520677/

相关文章:

objective-c - 如果 drawRect 被覆盖,iOS subview 显示为黑色矩形

ios - 将UserTrackingMode 设置为 MKUserTrackingModeFollow 而不更改缩放级别

ios - 运行 ios 9 通知时崩溃

ios - Swift 无法更改 xib uiview 中的 ImageView 框架

ios - 获得Facebook等周边地区名称的简单方法?

objective-c - UIImagePickerControllerMediaURL 对于照片总是 nil

iOS GCM GCMPubSub 取消订阅错误 7 - 未知错误

ios - 利用外部加载 Nib 中的 IBOutlets/IBActions

iOS 应用 View 选择

ios - 将 UIView 单元格组件的背景颜色更改为绿色不会将组件呈现为绿色,