当iOS中的属性正确时,UITextfield文本显示为左对齐?

时间:2017-12-29 13:22:33

标签: ios swift localization uitextfield text-alignment

我正在开发一个具有本地化的英语/阿拉伯语应用程序。在一个文本字段中,我将textAlignment属性设置为right。但内容,数字,显示在右侧。我通过调试textAlignment属性值对它进行了双重检查,确实是right

我已经以编程方式设置了对齐属性,因为它将根据语言选择(即按钮点击)进行更改。然后我在其中设置值并显示为右对齐。

当我选择文本字段时,突然内容移动到右侧并显示为右对齐。

我使用以下行以编程方式将布局更改为RTL和LTL:

UIView.appearance().semanticContentAttribute = .forceRightToLeft

我找不到解决方案。

2 个答案:

答案 0 :(得分:1)

尝试这种方法

 if isLangEn
    { 
        self.textF.textAlignment = NSTextAlignment.left  
        self.parentViewOfTextF.semanticContentAttribute = UISemanticContentAttribute.forceLeftToRight  
    }
    else
    {   
        self.textF.textAlignment = NSTextAlignment.right
        self.parentViewOfTextF.semanticContentAttribute = UISemanticContentAttribute.forceRightToLeft  
    }

答案 1 :(得分:0)

要在更改语言时设置Label和Textfields文本的对齐方式,请使用以下代码行:

  1. 检查应用语言:

    class Language {
    
      static var isArabicLanguage : Bool {
        get {
               return currentAppleLanguage() == "ar"
         }
       }
    }
    
  2. 创建UIViewController的扩展名:

    extension UIViewController {
    
    //Align Textfield Text
    
    func loopThroughSubViewAndAlignTextfieldText(subviews: [UIView]) {
    if subviews.count > 0 {
        for subView in subviews {
            if subView is UITextField && subView.tag <= 0{
                let textField = subView as! UITextField
                textField.textAlignment = Language.isArabicLanguage ? .right: .left
            } else if subView is UITextView && subView.tag <= 0{
                let textView = subView as! UITextView
                textView.textAlignment = Language.isArabicLanguage ? .right: .left
    
            }
    
            loopThroughSubViewAndAlignTextfieldText(subviews: subView.subviews)
        }
      }
    }
    
    
    //Align Label Text
    func loopThroughSubViewAndAlignLabelText(subviews: [UIView]) {
    if subviews.count > 0 {
        for subView in subviews {
            if subView is UILabel && subView.tag <= 0 {
                let label = subView as! UILabel
                label.textAlignment = Language.isArabicLanguage ? .right : .left
            }
            loopThroughSubViewAndAlignLabelText(subviews: subView.subviews)
        }
       }
      }
    }
    
  3. 创建一个继承自UIViewController的新类Localizer,它帮助我们设置每个viewController的对齐。

    class LocalizerViewController: UIViewController {
    
       override func viewDidLoad() {
          super.viewDidLoad()
    
          self.loopThroughSubViewAndAlignTextfieldText(subviews: self.view.subviews)
          self.loopThroughSubViewAndAlignLabelText(subviews: self.view.subviews)
      }
    }
    
  4. 现在,将所有ViewController继承到LocalizerViewController:

    class myViewController: LocalizerViewController {
           override func viewDidLoad() {
               super.viewDidLoad()
          }
    }
    
  5. 它会根据您的应用语言将所有标签和文本字段文本右对齐或左对齐。