swift 计算label的行数方法

时间:2022-06-27 08:33:50

这主要针对是 cell上label自适应高度,

let lineSpaceKey = "lineSpaceKey"

extension UILabel{

var lineSpace :CGFloat?{

set{

objc_setAssociatedObject(self, lineSpaceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

}

get{

return (objc_getAssociatedObject(self, lineSpaceKey) as? CGFloat)

}

}

//label 内容行数  这的size 是label 的宽和高  lineSpace 是行间距

func textNumLinesWithHeight(size:CGSize) -> CGFloat {

let paragraphStyle = NSMutableParagraphStyle()

paragraphStyle.lineBreakMode = self.lineBreakMode

paragraphStyle.alignment = self.textAlignment

if self.lineSpace == nil {

self.lineSpace = 0

}

paragraphStyle.lineSpacing = self.lineSpace!

let attributes = [NSFontAttributeName : self.font,

NSParagraphStyleAttributeName : paragraphStyle];

let contentSize = self.text!.boundingRectWithSize(size, options: [.UsesFontLeading,.UsesLineFragmentOrigin] , attributes: attributes, context: nil).size

let labelNumber = contentSize.height / self.font.lineHeight

return labelNumber

}

}