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

The reason this is true is that the SwiftUI
Textview does not support allAttributedStringattributes.In particular, it only supports the attributes defined in
AttributeScopes.SwiftUIAttributes, which does not include.paragraphStyle.Currently the only solution is dropping to UIKit/AppKit, as you found for yourself.
This is some useful background reading: https://dimillian.medium.com/swiftui-attributedstring-is-not-there-yet-63d49e9f9c16