How to find actual number of lines of UILabel?

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

    Swift 5 (IOS 12.2)

    Get max number of lines required for a label to render the text without truncation.

    extension UILabel {
        var maxNumberOfLines: Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
            let text = (self.text ?? "") as NSString
            let textHeight = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil).height
            let lineHeight = font.lineHeight
            return Int(ceil(textHeight / lineHeight))
        }
    }
    

    Get max number of lines can be displayed in a label with constrained bounds. Use this property after assigning text to label.

    extension UILabel {
        var numberOfVisibleLines: Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
            let textHeight = sizeThatFits(maxSize).height
            let lineHeight = font.lineHeight
            return Int(ceil(textHeight / lineHeight))
        }
    }
    

    Usage

    print(yourLabel.maxNumberOfLines)
    print(yourLabel.numberOfVisibleLines)
    

提交回复
热议问题