动态高度uilabel

Muz*_*san 1 uilabel ios

我试图在文本宽度改变时动态地改变uilabel高度,但是当我尝试使用这条线"white wallington hall"时出现问题.基本上它计算uilabel中2行中的宽度,但当它显示在两行中时,它看起来像这样:

"white   
 wallington h..."
Run Code Online (Sandbox Code Playgroud)

示例代码:

 UILabel* lbl_Property = [[UILabel alloc]init];
   [lbl_Property setFont:[UIFont fontWithName:@"Arial" size:10]];
   [lbl_Property setNumberOfLines:0];
   [lbl_Property setText:[arr_SubDetail objectAtIndex:x]];
   UIFont* font = [UIFont fontWithName:@"Arial" size:10];
   CGSize stringSize = [lbl_Property.text sizeWithFont:font];
   CGFloat width = stringSize.width;


   [lbl_Property setFrame:CGRectMake(lbl_Property.frame.origin.x, lbl_Property.frame.origin.y, lbl_Property.frame.size.width,5+lbl_Property.frame.size.height*(ceilf(width/110)))];
Run Code Online (Sandbox Code Playgroud)

实际上在"白色"之后有一个空格并且"wallington"不在该行中,所以它会在一个新的行上,但它没有显示完整的文本

如何让它显示正确?

Chi*_*iya 5

试试吧....

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                    constrainedToSize:maximumLabelSize 
                    lineBreakMode:yourLabel.lineBreakMode]; 

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
Run Code Online (Sandbox Code Playgroud)