takaishota
5/25/2017 - 2:43 PM

UILabelの行数を返す

UILabelの行数を返す

extension UILabel {
    func lineNumber(text: String, font: UIFont = UIFont.systemFont(ofSize: 17)) -> Int {
        let oneLineRect  =  "a".boundingRect(with: bounds.size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        let boundingRect = text.boundingRect(with: CGSize(bounds.size.width, CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        
        return Int(boundingRect.height / oneLineRect.height)
    }
}