Adjust UILabel height depending on the text

前端 未结 30 1782
走了就别回头了
走了就别回头了 2020-11-22 03:53

Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players m

30条回答
  •  情深已故
    2020-11-22 04:36

    My approach to compute the dynamic height of UILabel.

        let width = ... //< width of this label 
        let text = ... //< display content
    
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.preferredMaxLayoutWidth = width
    
        // Font of this label.
        //label.font = UIFont.systemFont(ofSize: 17.0)
        // Compute intrinsicContentSize based on font, and preferredMaxLayoutWidth
        label.invalidateIntrinsicContentSize() 
        // Destination height
        let height = label.intrinsicContentSize.height
    

    Wrap to function:

    func computeHeight(text: String, width: CGFloat) -> CGFloat {
        // A dummy label in order to compute dynamic height.
        let label = UILabel()
    
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.font = UIFont.systemFont(ofSize: 17.0)
    
        label.preferredMaxLayoutWidth = width
        label.text = text
        label.invalidateIntrinsicContentSize()
    
        let height = label.intrinsicContentSize.height
        return height
    }
    

提交回复
热议问题