简体   繁体   中英

How to set the fontsize programmatically to fit numberOflines value in swift4

I have two UILabels named headingLabel and descriptionLabel whose number of lines is 3 and 5 respectively. Now I want the font-size of the text to change and fit into the numberOfLines where the text varies based on some networking json data received.

iphone5s中的文字图片 iphoneX 中的文字图片

 here is my code

    let headingLabel : UILabel = {
        let hl = UILabel()
        hl.translatesAutoresizingMaskIntoConstraints = false
        hl.text = "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor"

        hl.textColor = .black
        hl.lineBreakMode = NSLineBreakMode.byWordWrapping
        hl.numberOfLines = 3;
        hl.sizeToFit()
        hl.clipsToBounds = true
        hl.font = hl.font.withSize(20)

        return hl
    }()

    let descriptionLabel : UILabel = {
        let dl = UILabel()
        dl.translatesAutoresizingMaskIntoConstraints = false
        dl.text = "Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolorLorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor sit amet amet Lorem ipsum dolor"
        dl.textColor = .black
        dl.lineBreakMode = NSLineBreakMode.byWordWrapping
        dl.numberOfLines = 5
        dl.font = dl.font.withSize(18)
        dl.sizeToFit()
        dl.clipsToBounds = true
        dl.alpha = 0.8
        return dl
    }()

Use Autoshrink to adjust text into label frame.

Authoshrink with Minimum Font Size

在此处输入图片说明

Authoshrink with Minimum Font Scale

在此处输入图片说明

Apple document about UILabel - Autoshrink

Determines whether the label adjusts the appearance of the text before resorting to truncation. Choose Minimum Font Scale and enter a value to allow the label to reduce the font size to fit the text. Enable Tighten Letter Spacing to allow the label to reduce intercharacter spacing. Access these values at runtime with the minimumScaleFactor and allowsDefaultTighteningForTruncation properties, respectively.

Please give:

dl.numberOfLines =  0

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM