Figure out size of UILabel based on String in Swift

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

    Swift 5:

    If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

    extension UILabel {
        func getSize(constrainedWidth: CGFloat) -> CGSize {
            return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
        }
    }
    

    You can use it like this:

    let label = UILabel()
    label.text = "My text\nIs\nAwesome"
    let labelSize = label.getSize(constrainedWidth:200.0)
    

    Works for me

提交回复
热议问题