How to calculate the size of a UIFont when text in label is constrained down to fit width?

后端 未结 1 576
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 22:54

Imagine a UILabel, which is 200 pixels wide and 50 pixels high. The label has text inside, and the label makes the text smaller so that it fits into the label. But now, how

相关标签:
1条回答
  • 2021-01-02 23:24

    If you pass the size of the UILabel and the breakMode, etc. to:

    CGSize  size = [label.text sizeWithFont:label.font minFontSize:10 actualFontSize:&actualFontSize forWidth:200 lineBreakMode:UILineBreakModeTailTruncation];
    

    actualFontSize should be what you are looking for.

    UPDATE:

    The above has been deprecated. The method to use now is:

    - (CGRect)textRectForBounds:(CGRect)bounds
         limitedToNumberOfLines:(NSInteger)numberOfLines
    

    Here's an example

    CGSize  size = [label textRectForBounds:label.bounds
         limitedToNumberOfLines:1].size;
    
    0 讨论(0)
提交回复
热议问题