gpt4 book ai didi

ios - 在 View 中动态添加多行标签

转载 作者:行者123 更新时间:2023-11-29 10:25:30 24 4
gpt4 key购买 nike

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

}

它是这样的:

enter image description here

关于ios - 在 View 中动态添加多行标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32531730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com