UILabel auto resize on basis of text to be shown

后端 未结 10 1893
余生分开走
余生分开走 2021-01-29 22:44

I\'m working on an application, in which I\'m required to autoresize the text area on basis of text to be displayed.

Firstly, I\'m not sure for this either I should use

10条回答
  •  抹茶落季
    2021-01-29 23:43

    Because you're going to use this solution countless times in your app, do the following:

    1) Create a directory called extensions and add a new file inside called UILabel.swift with the following code:

    import UIKit
    
    extension UILabel {
        func resizeToText() {
            self.numberOfLines = 0
            self.sizeToFit()
        }
    }
    

    2) In your app code, define the label width you want and just call resizeToText():

    label.frame.size.width = labelWidth
    label.resizeToText()
    

    This will maintain width while increasing the height automatically.

提交回复
热议问题