Thursday, September 11, 2025
HomeiOS Developmentswift - How can I apply justified textual content alignment with RTL...

swift – How can I apply justified textual content alignment with RTL or LTR course to a UITextView in iOS?


I need to apply justified textual content alignment to a UITextView and set the textual content course to both RTL (Proper-to-Left) or LTR (Left-to-Proper). I am engaged on a multilingual app and want to make sure that textual content is displayed appropriately based mostly on the language course.

Here is what I’ve to date:


import UIKit

extension UITextView {
    
    func applyJustifiedStyle(_ course: TextDirection) {
        guard let fontName = self.font?.fontName else {
            print("Font identify isn't set.")
            return
        }
        
        let fontSize = self.font?.pointSize ?? UIFont.systemFontSize
        
        let type = NSMutableParagraphStyle()
        type.alignment = .justified
        type.lineSpacing = fontSize / 1.5
        
        change course {
        case .LTR:
            type.baseWritingDirection = .leftToRight
            self.semanticContentAttribute = .forceLeftToRight
        case .RTL:
            type.baseWritingDirection = .rightToLeft
            self.semanticContentAttribute = .forceRightToLeft
        }
        
        let attributes: [NSAttributedString.Key: Any] = [
            .paragraphStyle: style,
            .baselineOffset: 0,
            .foregroundColor: UIColor.label, // Optional
            .font: UIFont(name: fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
        ]
        
        if let textual content = self.textual content {
            let attributedString = NSAttributedString(string: textual content, attributes: attributes)
            self.attributedText = attributedString
        }
    }
}


Utilization :


textView.textual content = "some textual content"
textView.applyJustifiedStyle(.RTL)

Nonetheless, I’m undecided if that is the perfect method, or if there are any pitfalls I ought to concentrate on. Can somebody please present insights or recommend enhancements?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments