How to find actual number of lines of UILabel?

前端 未结 14 2245
灰色年华
灰色年华 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:03

    Firstly set text in UILabel

    First Option :

    Firstly calculate height for text according to font :

    NSInteger lineCount = 0;
    CGSize labelSize = (CGSize){yourLabel.frame.size.width, MAXFLOAT};
    CGRect requiredSize = [self boundingRectWithSize:labelSize  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: yourLabel.font} context:nil];
    

    Now calculate number of lines :

    int charSize = lroundf(yourLabel.font.lineHeight);
    int rHeight = lroundf(requiredSize.height);
    lineCount = rHeight/charSize;
    NSLog(@"No of lines: %i",lineCount);
    

    Second Option :

     NSInteger lineCount = 0;
     CGSize textSize = CGSizeMake(yourLabel.frame.size.width, MAXFLOAT);
     int rHeight = lroundf([yourLabel sizeThatFits:textSize].height);
     int charSize = lroundf(yourLabel.font.lineHeight);
     lineCount = rHeight/charSize;
     NSLog(@"No of lines: %i",lineCount);
    
    0 讨论(0)
  • 2020-11-27 14:03

    Swift 5.2

    The main point to make it work for me was to call label.layoutIfNeeded() because I was using autoLayout, otherwise it doesnt work.

    func actualNumberOfLines(label: UILabel) -> Int {
            // You have to call layoutIfNeeded() if you are using autoLayout
            label.layoutIfNeeded()
    
            let myText = label.text! as NSString
    
            let rect = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
            let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: label.font as Any], context: nil)
    
            return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
        }
    

    Credits to: https://gist.github.com/fuxingloh/ccf26bb68f4b8e6cfd02, which provided the solution in an older swift version, and for mentioning the importance of layoutIfNeeded().

    0 讨论(0)
提交回复
热议问题