ios swift5 UIlabel calculates the height and width according to the text (content), the height is adaptive, but the height boundingRectWithSize must be known in advance

0. Add a method to the extension of the label, first set the text of the label, pass in the width, you can get the height of the label (it is an optimization of 1 and 2)

extension UILabel {
    
    
    func labelHeight(width:CGFloat)->CGFloat{
    
    
        let dic = [NSAttributedString.Key.font : font]
        let size = CGSize(width: width, height: 0)
        let rect = text!.boundingRect(with: size, options: [.usesFontLeading,.usesLineFragmentOrigin], attributes: dic, context: nil)
        return CGFloat(ceilf(Float(rect.size.height)))
    }
}

Please add image description

1. The screenshot below measures the height calculated by the text, and the height of the label (set to 200) when it is actually displayed, both are 255, which is consistent

Please add image description

2. Code

class tableViewTestVC: UIViewController{
    
    
    lazy var label:UILabel = {
    
    
       let label = UILabel()
        label.backgroundColor = .yellow
        let font =  UIFont.init(name: "PingFang SC", size: 14)!
        label.font = font
        label.numberOfLines = 0
        let str:NSString = "但是公司的高度是广东省公司的广东省高速度来开个大帅哥多撒谎个爱好就跟他说噶三公司噶是的刚好是我哥如果黑暗如果坏都干撒降低公司及嘎斯进欧冠赛欧结果就赛欧国际韶关;可垃圾费;阿尔加两块;三个身高萨嘎干撒的公司的高度上收到公司的公司都给ID搜狗破is打个屁偶是东莞IP手动皮革是滴哦苹果是滴哦苹果度搜皮为欧公司的漂漂是第三个是干撒噶是的噶虽然刚撒旦个撒公司的公司的高度"
        label.text = str as String
        let attriText = NSMutableAttributedString(string: str as String)
        let dic = [NSAttributedString.Key.font : font]
        let size = CGSize(width: 200, height: 0)
        let rect = str.boundingRect(with: size, options: [.usesFontLeading,.usesLineFragmentOrigin], attributes: dic, context: nil)
        printXY(label, obj: self, line: #line)
        printXY(rect, obj: self, line: #line)
        printXY(ceilf(Float(rect.size.height)), obj: self, line: #line)
        return label
    }()
    override func viewDidAppear(_ animated: Bool) {
    
    
        printXY(label, obj: self, line: #line)
    }
    override func viewDidLoad() {
    
    
        super.viewDidLoad()
        view.addSubview(label)
        label.snp.makeConstraints {
    
     (make) in
            make.top.equalToSuperview().offset(30)
            make.left.equalToSuperview().offset(10)
            make.width.equalTo(200)
        }
    }
    
}

3. Reference blog:

iOS Tips Use boundingRectWithSize to calculate content height
Understand the usage and meaning of each option of NSStringDrawingOptions
[iOS development] Calculate height based on text in
iOS iOS development | Simple and realistic cell height adaptive content and advance calculation and cache cell height

Guess you like

Origin blog.csdn.net/baidu_40537062/article/details/123915035