Skip to content

Instantly share code, notes, and snippets.

@HereOrCode
Last active May 11, 2022 09:19
Show Gist options
  • Save HereOrCode/243eb7daa7b1dd063c357bb0aea6aa73 to your computer and use it in GitHub Desktop.
Save HereOrCode/243eb7daa7b1dd063c357bb0aea6aa73 to your computer and use it in GitHub Desktop.
UILabel and UITextView add line spacing
import UIKit
protocol LabelLineSpacingable where Self: UILabel {
func lineSpacing(_ value: CGFloat)
}
protocol TextViewLineSpacingable where Self: UITextView {
func lineSpacing(_ value: CGFloat,
content: String,
withColor color: UIColor?,
withFontSize fontSize: CGFloat?)
}
extension LabelLineSpacingable {
func lineSpacing(_ spacingValue: CGFloat) {
// MARK: - Check if there's any text
guard let textString = text else { return }
// MARK: - Create "NSMutableAttributedString" with your text
let attributedString = NSMutableAttributedString(string: textString)
// MARK: - Create instance of "NSMutableParagraphStyle"
let paragraphStyle = NSMutableParagraphStyle()
// MARK: - Actually adding spacing we need to ParagraphStyle
paragraphStyle.lineSpacing = spacingValue
paragraphStyle.lineBreakMode = .byTruncatingTail
// MARK: - Adding ParagraphStyle to your attributed String
attributedString.addAttribute(
.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: attributedString.length))
// MARK: - Assign string that you've modified to current attributed Text
attributedText = attributedString
}
}
extension TextViewLineSpacingable {
func lineSpacing(_ value: CGFloat, content: String, withColor color: UIColor?, withFontSize fontSize: CGFloat?) {
let style = NSMutableParagraphStyle()
style.lineSpacing = value
style.alignment = .left
let color = color ?? .white
let fontSize = fontSize ?? 16
attributedText = NSAttributedString(string: content,
attributes: [
.paragraphStyle: style,
.foregroundColor: color,
.font: UIFont.systemFont(ofSize: fontSize)
])
}
}
import UIKit
extension UILabel: LabelLineSpacingable {}
extension UITextView: TextViewLineSpacingable {}

How to use

// UILabel
label.lineSpacing(8)

// UITextView
textView.lineSpacing(10, content: "demo demo demo", withColor: .white, withFontSize: 16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment