Get the NSString height

前端 未结 2 704
眼角桃花
眼角桃花 2020-12-10 04:35

I have an NSString, and I want to know its height to create an appropriate UILabel.

Doing this

NSString *string = @\"this is an example\"; 
CGSize si         


        
2条回答
  •  渐次进展
    2020-12-10 05:26

    The reason what you're doing doesn't work as you would expect is because

    – sizeWithFont:forWidth:lineBreakMode: 
    

    is for "Computing Metrics for a Single Line of Text" whereas

    -sizeWithFont:constrainedToSize:lineBreakMode:
    

    is for "Computing Metrics for Multiple Lines of Text". From the documentation:

    Computing Metrics for a Single Line of Text

    – sizeWithFont:
    – sizeWithFont:forWidth:lineBreakMode:
    – sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
    

    Computing Metrics for Multiple Lines of Text

    – sizeWithFont:constrainedToSize:
    – sizeWithFont:constrainedToSize:lineBreakMode:
    

    Try using -sizeWithFont:constrainedToSize:lineBreakMode: instead, e.g. this is what I usually do:

    CGSize maximumLabelSize = CGSizeMake(353,9999);
    
    CGSize expectedLabelSize = [string sizeWithFont:label.font                        
                                  constrainedToSize:maximumLabelSize 
                                      lineBreakMode:label.lineBreakMode]; 
    
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    

提交回复
热议问题