I have a string of text of Arabic and English words, I need to add attribute using NSMutableAttributedString
and add paragraph styling with NSMutableParagraphStyle
. The problem is paragraph style doesn't apply to the text and not sure why. First I am detecting Arabic characters and changing the color (it works), and then trying to change line spacing or alignment which is not working. Here is the code:
let arabicChars = try? NSRegularExpression(pattern: "[\\u0600-\\u06FF\\u0750-\\u077F\\u08A0-\\u08FF\\uFB50-\\uFDFF\\uFE70-\\uFEFF\\s]+", options: [])
arabicChars?.enumerateMatches(in: pureText, options: [], range: range) { (result, _, _) in
if let subStringRange = result?.range(at: 0) {
stringText.addAttribute(.foregroundColor, value: UIColor(.brown), range: subStringRange)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .right
paragraphStyle.lineSpacing = 1.2
paragraphStyle.lineHeightMultiple = 1.2
stringText.addAttribute(.paragraphStyle, value: paragraphStyle, range: subStringRange)
stringText.addAttribute(.font, value: UIFont(name: "CustomFont", size: 16)!, range: subStringRange)
}
}
And then using the function in SwiftUI like this:
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 15) {
Text(word.word?.capitalized ?? "")
.font(.system(size: 32, weight: .bold, design: .serif))
Text(AttributedString(applyAttributedStyle(word.meaning)))
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal)
}
}
Here is the image that shows current result (left) vs right result:
Edit 1: It works fine with UIKit's UITextView but not working on SwiftUI's Text
Edit 2:
I have fixed the issue using UIViewRepresentable
with UITextView
Apple not suppourt
.natrual
in SwiftUI, they add suppourt for AttributedString in SwiftUI butparagraphstyle
not suppourtedThere is a trick that is working and depend only in pure SwiftUI I have created it here
for Text use NaturalText
for TextEditor use NaturalTextEditor
how I solved this issue ?
1- I checked the app language
2- I checked the text content itself depend on first letters using Apple AI NaturalLanguage
3- depend on app language if it's English that mean leading is left and trailing is right, but if app language is Arabic that mean leading is right and trailing is left
so now I know if app lagnuage is English but text is Arabic it will be RTL if the text is english it will be LTR same thing if the app lagnuage is Arabic, if the text is English it will be LTR but if the text is arabic it will be RTL
I'm using this code in all my production apps, working 100% fine
the result will be as you want it