Figure out size of UILabel based on String in Swift

后端 未结 11 1412
执笔经年
执笔经年 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:25

    Heres a simple solution thats working for me... similar to some of the others posted, but it doesn't not include the need for calling sizeToFit

    Note this is written in Swift 5

    let lbl = UILabel()
    lbl.numberOfLines = 0
    lbl.font = UIFont.systemFont(ofSize: 12) // make sure you set this correctly 
    lbl.text = "My text that may or may not wrap lines..."
    
    let width = 100.0 // the width of the view you are constraint to, keep in mind any applied margins here
    
    let height = lbl.systemLayoutSizeFitting(CGSize(width: width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height
    

    This handles line wrapping and such. Not the most elegant code, but it gets the job done.

提交回复
热议问题