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

Dynamically adding multiline label in a view

我正在我的应用程序中动态创建 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];

    }

与其使用 (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];

}

它是这样的: