Friday, August 2, 2024
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 wish 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 accurately primarily based on the language course.

This is what I’ve thus far:


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)

Nevertheless, I’m unsure if that is the perfect strategy, or if there are any pitfalls I ought to pay attention to. Can somebody please present insights or recommend enhancements?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments