DeyaEldeen
DeyaEldeen

Reputation: 11807

how to prevent UITextfield from changing alignment when input language is RTL/Arabic?

The app language is English, the illustration on the left shows UITextfields content aligned to the left.. which is normal, but when the user selects an RTL/Arabic input language, the fields alignment are flipped automatically, how to force the alignment to be left disregarding the input language direction?

EDIT :

I tried this, and it's not solving the problem

    let _beginningOfDocument = fieldPassword!.beginningOfDocument
    let _endOfDocument = fieldPassword!.endOfDocument

    fieldPassword!.setBaseWritingDirection(.leftToRight, for: fieldPassword!.textRange(from: _beginningOfDocument , to: _endOfDocument )! )

swift alignment for keyboards uitextfields rtl

Upvotes: 4

Views: 4886

Answers (4)

Braham Youssef
Braham Youssef

Reputation: 487

To be honest I tried all of them and doesn't work for me because it's related to the view hierarchy . For more information, you can read this note

Note iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

So try this one, it worked for me:

extension UITextField {
   open override func awakeFromNib() {
    super.awakeFromNib()
    if Utilities.getCurrentLanguage() == "ar" {
        if textAlignment == .natural {
            self.textAlignment = .right
        }
      }
   }
 }

By the way, "Utilities.getCurrentLanguage()" is a function to get the current language.

Upvotes: 5

Sourabh Kumbhar
Sourabh Kumbhar

Reputation: 1054

In Swift 4

textField.semanticContentAttribute = UISemanticContentAttribute.forceLeftToRight

Upvotes: 2

DeyaEldeen
DeyaEldeen

Reputation: 11807

It came out that some library I was using caused this effect, it's MOLH library, it uses method swizzling, this is why this was difficult to debug...

I will be making a pull request to it soon to make this effect optional...

func listenToKeyboard() {
    NotificationCenter.default.removeObserver(self, name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(inputModeDidChange), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
}

@objc func inputModeDidChange(_ notification: Notification) {
    if let language = self.textInputMode?.primaryLanguage, MOLHLanguage.isRTLLanguage(language: language) {
        self.textAlignment = .right
    } else {
        self.textAlignment = .left
    }
}

Thanks.

Upvotes: 3

dduyduong
dduyduong

Reputation: 122

In your app delegate, add this:

if #available(iOS 9.0, *) { UIView.appearance().semanticContentAttribute = .forceLeftToRight }

Upvotes: -2

Related Questions