【问题标题】:iOS - Create custom UILabel and add them to UIViewiOS - 创建自定义 UILabel 并将它们添加到 UIView
【发布时间】:2012-03-20 16:53:53
【问题描述】:

我想在 UIView 中实现这样的功能:

我创建了一个带有自定义 init 方法的自定义 UILabel:

@implementation TagLabel
- (id)init {
    self = [super initWithFrame:CGRectMake(0, 0, 100, 40)];
    if (self) {
        self.layer.borderColor = [UIColor whiteColor].CGColor;
        self.layer.borderWidth = 4.0;
        self.layer.cornerRadius = 4;
        self.backgroundColor = [UIColor greenColor];
        self.textColor = [UIColor whiteColor];
        self.textAlignment = UITextAlignmentCenter;
    }
    return self;
}
@end

然后我创建每个标签并将其添加到视图中,如下所示:

for (NSDictionary *tag in [self.voicenote objectForKey:@"Tag"]) {
        TagLabel *tagLabel = [[TagLabel alloc] init];
        tagLabel.text = [tag objectForKey:@"tag"];
        [self.tagsView addSubview:tagLabel];
    }

然而我得到的只是一个空白的 UIView,我错过了什么吗?有没有更好的方法来实现这一点?

编辑:一个问题解决了,修改了UILabel代码,直接把背景颜色设置为背景,现在就显示出来了,现在怎么才能让它们并排不重叠呢?

【问题讨论】:

    标签: ios uiview uilabel subview


    【解决方案1】:

    在您的 for 循环中,您需要为标签制作自定义框架并按照您想要的方式排列它们。 可能是这样的:

    CGRect frame = label.frame;
    frame.size.height = masterFrame.height;
    frame.origin.y = masterFrame.origin.y + masterFrame.size.height + 40;
    label.frame = frame;
    

    这是一个更长的方法。您也可以使用 [CGRect initWithFrame ...]

    初始化框架

    【讨论】:

      【解决方案2】:

      它们都被添加到父视图的相同位置

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多