Swift 5
class AttributedStrings {
private func paragraphStyle(alignment: NSTextAlignment, hyphenate: Bool) -> NSMutableParagraphStyle {
let style = NSMutableParagraphStyle()
style.hyphenationFactor = hyphenate ? 0.1 : 0
style.alignment = alignment
return style
}
func string(_ string: String, font: UIFont, color: UIColor, alignment: NSTextAlignment = .left, hyphenate: Bool = true) -> NSAttributedString {
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.paragraphStyle: paragraphStyle(alignment: alignment, hyphenate: hyphenate)
]
return NSAttributedString(string: string, attributes: attributes)
}
}
let attributedStrings = AttributedStrings()
let attributedString1 = attributedStrings.string("Hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black)
let attributedString2 = attributedStrings.string("Don't hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black, hyphenate: false)
let attributedString3 = attributedStrings.string("Center and hyphenate this", font: .boldSystemFont(ofSize: 24), color: .black, alignment: .center)
let label = UILabel()
label.attributedText = attributedString1
Since we can't subclass NSAttributedString
, consider making a vendor class that makes them for you. The key difference with my answer is the hyphenation factor. Hyphenation factor is a float between 0.0
and 1.0
. A factor of 1.0
will always hyphenate the word no matter what. A factor of 0.1
will only hyphenate the word if there isn't enough room on the next line to display it without hyphenation. But you can play with the factor to find a threshold that you like.