Search code examples
iosswiftuitextfieldarabicright-to-left

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


Solution

  • 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.