1

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

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

实际上,在“white”之后有一个空格,而“wallington”不在该行中,所以它换了一个新行,但它没有显示完整的文本

如何让它正确显示?

4

4 回答 4

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;
于 2013-04-08T06:38:37.637 回答
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

于 2013-04-06T06:53:13.423 回答
1

希望下面的代码可以工作

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

这里的宽度或高度必须是固定的..

于 2013-04-06T07:13:05.070 回答
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)

}
于 2016-10-07T13:06:58.380 回答