I made function that set line height and letter spacing in UILabel
.
extension UILabel {
func apply(lineHeight: CGFloat, letterSpacing: CGFloat = 0) {
let attributedString = NSMutableAttributedString(string: text ?? " ")
let range = NSMakeRange(0, attributedString.length)
// Line Height
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight
style.maximumLineHeight = lineHeight
attributedString.addAttribute(.paragraphStyle, value: style, range: range)
attributedString.addAttribute(.baselineOffset, value: (lineHeight - font.lineHeight) / 2, range: range)
// Letter Spacing
attributedString.addAttribute(.kern, value: letterSpacing, range: range)
attributedText = attributedString
}
}
And I apply that my label.
But something very strange happens.
All of the codes below are the same.
The only difference is when you change the label's text.
I can't understand why this is happening.
What's the problem?
override func viewDidLoad() {
super.viewDidLoad()
let label1 = UILabel()
label1.font = .systemFont(ofSize: 32, weight: .bold)
label1.apply(lineHeight: 48)
label1.text = "This is test1"
label1.translatesAutoresizingMaskIntoConstraints = false
let label2 = UILabel()
label2.text = "This is test2"
label2.font = .systemFont(ofSize: 32, weight: .bold)
label2.apply(lineHeight: 48)
label2.translatesAutoresizingMaskIntoConstraints = false
let label3 = UILabel()
label3.text = "This is test3"
label3.font = .systemFont(ofSize: 32, weight: .bold)
label3.apply(lineHeight: 48)
label3.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label1)
view.addSubview(label2)
view.addSubview(label3)
NSLayoutConstraint.activate([
label1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label1.centerYAnchor.constraint(equalTo: view.centerYAnchor),
label2.topAnchor.constraint(equalTo: label1.bottomAnchor, constant: 8),
label2.centerXAnchor.constraint(equalTo: label1.centerXAnchor),
label3.topAnchor.constraint(equalTo: label2.bottomAnchor, constant: 8),
label3.centerXAnchor.constraint(equalTo: label1.centerXAnchor)
])
}