How to find actual number of lines of UILabel?

前端 未结 14 2407
灰色年华
灰色年华 2020-11-27 13:10

How can I find the actual number of lines of a UILabel after I have initialized it with a text and a font? I have set

14条回答
  •  佛祖请我去吃肉
    2020-11-27 14:02

    The other answers here don't respect the numberOfLines property of UILabel when it is set to something other than 0.

    Here's another option you can add to your category or subclass:

    - (NSUInteger)lineCount
    {
        CGSize size = [self sizeThatFits:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)];
        return MAX((int)(size.height / self.font.lineHeight), 0);
    }
    

    Some notes:

    • I'm using this on a UILabel with attributed text, without ever actually setting the font property, and it's working fine. Obviously you would run into issues if you were using multiple fonts in your attributedText.
    • If you are subclassing UILabel to have custom edge insets (for example by overriding drawTextInRect:, which is a neat trick I found here), then you must remember to take those insets into account when calculating the size above. For example: CGSizeMake(self.frame.size.width - (self.insets.left + self.insets.right), CGFLOAT_MAX)

提交回复
热议问题