Reputation: 101
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.
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
Reputation: 79776
Use Autoshrink to adjust text into label frame.
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