I have a UILabel
that will vary in number of lines. I'm using a custom font, and want to set the line height of this label to something >1.
Asked
Active
Viewed 904 times
2

Austin Berenyi
- 1,013
- 2
- 13
- 25
-
3Possible duplicate of [How to Increase Line spacing in UILabel in Swift](https://stackoverflow.com/questions/39158604/how-to-increase-line-spacing-in-uilabel-in-swift) – Sneha Sep 11 '17 at 03:42
-
He is asking for lineHeight, not line spacing, they are different – Lê Vũ Huy Apr 08 '21 at 04:55
1 Answers
1
I'm not really familiar with KVO, but I use Rx, so I can suggest using this
import UIKit
import RxSwift
import RxCocoa
extension UILabel {
private func setLineHeight(lineHeight: CGFloat) {
var attributeStringInitial: NSMutableAttributedString?
var textInitial: String?
if let text_ = self.text {
attributeStringInitial = NSMutableAttributedString(string: text_)
textInitial = text_
} else if let text_ = self.attributedText {
attributeStringInitial = NSMutableAttributedString(attributedString: text_)
textInitial = text_.string
}
guard let attributeString = attributeStringInitial,
let text = textInitial
else { return }
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, text.count))
self.attributedText = attributeString
}
func setLineHeight(lineHeight: CGFloat, disposeBag: DisposeBag) {
rx.observe(String.self, "text")
.subscribe(onNext: { [weak self] text in
self?.setLineHeight(lineHeight: 10)
})
.disposed(by: disposeBag)
}
}

Daniyar
- 21
- 5