kamalakshi hegde
kamalakshi hegde

Reputation: 101

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.

image for text in iphone5s image for text in 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
    }()

Upvotes: 2

Views: 235

Answers (2)

Krunal
Krunal

Reputation: 79776

Use Autoshrink to adjust text into label frame.

Authoshrink with Minimum Font Size

enter image description here

Authoshrink with Minimum Font Scale

enter image description here

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.

Upvotes: 1

Hardik Bar
Hardik Bar

Reputation: 1760

Please give:

dl.numberOfLines =  0

enter image description here

Upvotes: 0

Related Questions