40.UILabel计算高度

第一种方法:计算label内容,适用于计算富文本高度

func getHeightss(temp: String, font: CGFloat) -> CGFloat {
   let string = NSString.init(string: temp)
   let size = string.boundingRect(with: CGSize.init(width: SCREEN_WIDTH - 20 * SCALE_WIDTH, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: font)], context: nil)
   return size.height
}

加上行间距

func getHeightss(temp: String, font: CGFloat) -> CGFloat {
        
   let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 1
        
   let string = NSString.init(string: temp)
   let size = string.boundingRect(with: CGSize.init(width: SCREEN_WIDTH - 20 * SCALE_WIDTH, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: font),NSAttributedString.Key.paragraphStyle:paragraphStyle], context: nil)
   return size.height
}

第二种:计算label的高度和每行的高度,适用于一般label

func getHeight(temp: String, font: CGFloat) -> (CGFloat,CGFloat) {
        
     let label = UILabel.init()
     label.font = UIFont.systemFont(ofSize: font * SCALE_WIDTH)
     label.text = temp
     label.numberOfLines = 0
     label.sizeToFit()
     label.preferredMaxLayoutWidth = SCREEN_WIDTH - 20 * SCALE_WIDTH
     let size = label.sizeThatFits(CGSize.init(width: SCREEN_WIDTH - 20 * SCALE_WIDTH, height: CGFloat.greatestFiniteMagnitude))
        return (size.height, label.font.lineHeight)
}

你可能感兴趣的:(40.UILabel计算高度)