动态高度uilabel

时间:2013-04-06 06:40:45

标签: ios uilabel

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

"white   
 wallington h..."

示例代码:

 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)))];

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

如何让它显示正确?

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分:3)

 int h=10;    
 UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];// See the 'h' value
 lbl_headitem.text = [headItemArray objectAtIndex:k];
 [lbl_headitem setTextAlignment:UITextAlignmentLeft];
 [lbl_headitem setBackgroundColor:[UIColor clearColor]];
 [lbl_headitem setTag:k];
 lbl_headitem.numberOfLines=0;  
 [lbl_headitem setTextColor:[UIColor redColor]];
 [lbl_headitem setFont:[UIFont fontWithName:@"Helvetica" size:18]];
 [scrollAttributes addSubview:lbl_headitem];
 h = h + size_txt_overview1.height;

确保label.numberOfLines设置为0

答案 2 :(得分:1)

希望以下代码可以正常工作

CGSize size = [str sizeWithFont:lbl.font constrainedToSize:CGSizeMake(204.0, 10000.0) lineBreakMode:lbl.lineBreakMode];

这里必须修复宽度或高度..

答案 3 :(得分:0)

func makeSizeSender(name:UILabel){

    let attributes = [NSFontAttributeName : name.font]
    let rect = name.text!.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
    name.frame = CGRectMake(contentView.frame.origin.x+30, 0, 200, rect.height+30);
    self.addSubview(name)

}