在视图中动态添加多行标签

时间:2015-09-11 20:34:46

标签: ios objective-c uilabel

我在我的应用中动态创建UILabel,以显示食谱的路线列表。标签填充正确显示所有项目一个接一个。

问题是文本在标签的下一行上出现时,它与下一个标签重叠。

我已将numberOfLines设置为0,并将lineBreakMode设置为NSLineBreakByWordWrapping。这有助于标签在多行显示文本。

我试图调整标签的高度,正如您将在代码中看到的那样,但它不起作用。

如何防止标签中的多行文字导致标签重叠?

以下是使用多行填充标签的代码:

//add all the directions to the uiview
    for (int i = 0; i < self.recipe.directions.count; i++)
    {
        UILabel *label =  [[UILabel alloc] initWithFrame: CGRectMake(0,(i+1)*25,280,25)];
        label.lineBreakMode = NSLineBreakByWordWrapping; //multiple lines in a label
        label.numberOfLines = 0;
        label.text =[NSString stringWithFormat: @"%@", self.recipe.directions[i]];
        [label sizeToFit]; // resize the width and height to fit the text
        NSLog(@"Actual height is: %f", label.frame.size.height); // Use this for spacing any further elements


        CGSize expectedLabelSize = [label.text sizeWithFont:label.font
                                            constrainedToSize:label.frame.size
                                                lineBreakMode:NSLineBreakByWordWrapping];
        //adjust the label the the new height.
        CGRect newFrame = label.frame;
        newFrame.size.height = expectedLabelSize.height;
        label.frame = newFrame;
        [self.directionsView addSubview:label];

    }

1 个答案:

答案 0 :(得分:2)

您应该存储最后一个标签的最低位置,而不是使用(i+1)*25的y位置初始化您的标签

CGFloat lastLabelBottomCoordinate = 25;
CGFloat spaceBetweenLines = 10;
for (int i = 0; i < 10; i++)
{
    UILabel *label =  [[UILabel alloc] initWithFrame: CGRectMake(0, lastLabelBottomCoordinate + spaceBetweenLines,280,25)];
    label.lineBreakMode = NSLineBreakByWordWrapping; //multiple lines in a label
    label.numberOfLines = 0;
    label.text =[NSString stringWithFormat: @"This is a very long text to see if the text have more than 2 lines"];
    [label sizeToFit]; // resize the width and height to fit the text
    NSLog(@"Actual height is: %f", label.frame.size.height); // Use this for spacing any further elements


    CGSize expectedLabelSize = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:@{NSFontAttributeName : label.font}
                                                        context:nil].size;
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;

    lastLabelBottomCoordinate = label.frame.origin.y + label.frame.size.height;
    [self.view addSubview:label];

}

它的外观如下:

enter image description here