How to find UILabel's number of Lines

后端 未结 7 720
悲哀的现实
悲哀的现实 2020-11-28 05:35

I displayed the text in UILabel by using wrap method. Now I want to need to find the how many number of line is there in UILabel.

If there is any possible way to fi

7条回答
  •  一生所求
    2020-11-28 06:12

    If you're looking for this answer in Swift 2+/iOS 8, it would look like this:

    func numberOfLinesInLabel(yourString: String, labelWidth: CGFloat, labelHeight: CGFloat, font: UIFont) -> Int {
    
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.minimumLineHeight = labelHeight
        paragraphStyle.maximumLineHeight = labelHeight
        paragraphStyle.lineBreakMode = .ByWordWrapping
    
        let attributes: [String: AnyObject] = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle]
    
        let constrain = CGSizeMake(labelWidth, CGFloat(Float.infinity))
    
        let size = yourString.sizeWithAttributes(attributes)
        let stringWidth = size.width
    
        let numberOfLines = ceil(Double(stringWidth/constrain.width))
    
        return Int(numberOfLines)
    }
    

提交回复
热议问题