Skip to content

Instantly share code, notes, and snippets.

@ahmedk92
Last active May 1, 2020 04:42
Show Gist options
  • Save ahmedk92/3152d99f7f2af62b711418bf6f3a560e to your computer and use it in GitHub Desktop.
Save ahmedk92/3152d99f7f2af62b711418bf6f3a560e to your computer and use it in GitHub Desktop.
Aligns paragraphs according to each's dominant language.
protocol ParagraphsNaturallyAligned: NSAttributedString {}
extension ParagraphsNaturallyAligned {
var paragraphsNaturallyAligned: Self {
let mutable = NSMutableAttributedString(attributedString: self)
mutable.alignParagraphsNaturally()
return (self is NSMutableAttributedString ? mutable : NSAttributedString(attributedString: mutable)) as! Self
}
}
extension ParagraphsNaturallyAligned where Self == NSMutableAttributedString {
func alignParagraphsNaturally() {
(string as NSString).enumerateSubstrings(in: NSRange(location: 0, length: length), options: .byParagraphs) { (paragaphContent, paragraphRange, _, _) in
guard let paragaphContent = paragaphContent else { return }
var existingParaghStyle: NSParagraphStyle?
self.enumerateAttribute(.paragraphStyle, in: paragraphRange, options: []) { (value, _, _) in
if let value = value as? NSParagraphStyle {
existingParaghStyle = value
}
}
let newParagraphStyle = existingParaghStyle == nil ? NSMutableParagraphStyle() : existingParaghStyle!.mutableCopy() as! NSMutableParagraphStyle
let isRTL = paragaphContent.isRTL
newParagraphStyle.baseWritingDirection = isRTL ? .rightToLeft : .leftToRight
if newParagraphStyle.alignment != .justified {
newParagraphStyle.alignment = isRTL ? .right : .left
}
self.addAttribute(.paragraphStyle, value: newParagraphStyle, range: paragraphRange)
}
}
}
extension NSAttributedString: ParagraphsNaturallyAligned {}
extension String {
var isRTL: Bool {
guard let dominantLanguage = NLLanguageRecognizer.dominantLanguage(for: self) else { return false }
let rtlLanguageIds = ["ar", "fa", "he", "ckb-IQ","ckb-IR", "ur", "ckb"] // credits: https://github.com/MoathOthman/MOLH/blob/313691443043f0da83502040f39b852cd9e3e0e8/Sources/MOLH/MOLHLanguage.swift#L120
return rtlLanguageIds.contains(dominantLanguage.rawValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment