// UILabel
label.lineSpacing(8)
// UITextView
textView.lineSpacing(10, content: "demo demo demo", withColor: .white, withFontSize: 16)
Last active
May 11, 2022 09:19
-
-
Save HereOrCode/243eb7daa7b1dd063c357bb0aea6aa73 to your computer and use it in GitHub Desktop.
UILabel and UITextView add line spacing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
]) | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UILabel: LabelLineSpacingable {} | |
extension UITextView: TextViewLineSpacingable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment