当输入语言为 RTL/Arabic 时,如何防止 UITextfield 更改对齐方式?

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

应用语言为英语,左图显示UITextfield的内容左对齐..这是正常的,但是当用户选择RTL/Arabic输入语言时,字段对齐方式自动翻转,如何强制保留对齐方式而不考虑输入语言方向?

编辑:

我试过了,没有解决问题

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

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

在您的应用委托中,添加:

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

结果是我使用的某些库导致了这种效果,它是 MOLH 库,它使用方法调配,这就是为什么很难调试的原因...

我将很快向它发出拉取请求,使这个效果成为可选的...

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
    }
}

谢谢。

在Swift 4

textField.semanticContentAttribute = UISemanticContentAttribute.forceLeftToRight

老实说,我尝试了所有这些,但对我不起作用,因为它与视图层次结构有关。欲了解更多信息,您可以阅读此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.

所以试试这个,它对我有用:

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

对了,"Utilities.getCurrentLanguage()"是获取当前语言的函数