Adjust UILabel height depending on the text

前端 未结 30 2335
走了就别回头了
走了就别回头了 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:26

    Swift 2:

        yourLabel.text = "your very long text"
        yourLabel.numberOfLines = 0
        yourLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        yourLabel.frame.size.width = 200
        yourLabel.frame.size.height = CGFloat(MAXFLOAT)
        yourLabel.sizeToFit()
    

    The interesting lines are sizeToFit() in conjunction with setting a frame.size.height to the max float, this will give room for long text, but sizeToFit() will force it to only use the necessary, but ALWAYS call it after setting the .frame.size.height .

    I recommend setting a .backgroundColor for debug purposes, this way you can see the frame being rendered for each case.

提交回复
热议问题