How to find actual number of lines of UILabel?

前端 未结 14 2376
灰色年华
灰色年华 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 13:50

    Following up on @Prince's answer, I now implemented a category on UILabel as follows (note that I corrected some minor syntax mistakes in his answer that wouldn't let the code compile):

    UILabel+Util.h

    #import 
    
    @interface UILabel (Util)
    - (NSInteger)lineCount;
    @end
    

    UILabel+Util.,

    #import "UILabel+Util.h"
    
    @implementation UILabel (Util)
    
    - (NSInteger)lineCount
    {
        // Calculate height text according to font
        NSInteger lineCount = 0;
        CGSize labelSize = (CGSize){self.frame.size.width, FLT_MAX};
        CGRect requiredSize = [self.text boundingRectWithSize:labelSize  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: self.font} context:nil];
    
        // Calculate number of lines
        int charSize = self.font.leading;
        int rHeight = requiredSize.size.height;
        lineCount = rHeight/charSize;
    
        return lineCount;
    }
    
    @end
    

提交回复
热议问题