Figure out size of UILabel based on String in Swift

后端 未结 11 1392
执笔经年
执笔经年 2020-11-22 13:35

I am trying to calculate the height of a UILabel based on different String lengths.

func calculateContentHeight() -> CGFloat{
    var maxLabelSize: CGSize         


        
11条回答
  •  有刺的猬
    2020-11-22 14:27

    This is my answer in Swift 4.1 and Xcode 9.4.1

    //This is your label
    let proNameLbl = UILabel(frame: CGRect(x: 0, y: 20, width: 300, height: height))
    proNameLbl.text = "This is your text"
    proNameLbl.font = UIFont.systemFont(ofSize: 17)
    proNameLbl.numberOfLines = 0
    proNameLbl.lineBreakMode = .byWordWrapping
    infoView.addSubview(proNameLbl)
    
    //Function to calculate height for label based on text
    func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat {
        let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text
    
        label.sizeToFit()
        return label.frame.height
    }
    

    Now you call this function

    //Call this function
    let height = heightForView(text: "This is your text", font: UIFont.systemFont(ofSize: 17), width: 300)
    print(height)//Output : 41.0
    

提交回复
热议问题