Figure out size of UILabel based on String in Swift

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

    This solution will help to calculate the height and width at runtime.

        let messageText = "Your Text String"
        let size = CGSize.init(width: 250, height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimateFrame = NSString(string: messageText).boundingRect(with:  size, options: options, attributes: [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue", size: 17)!], context: nil)
    

    Here you can calculate the estimated height that your string would take and pass it to the UILabel frame.

    estimateFrame.Width
    estimateFrame.Height 
    

提交回复
热议问题