应用程序本地化时,UITextField占位符的颜色不同

时间:2017-07-12 12:34:56

标签: ios swift uitextfield

我有一个非常奇怪的问题。我有一个UITextFieldIBInspectable var来改变它的占位符颜色,我这样做:

attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSForegroundColorAttributeName : color])

当应用方案设置为System languageEnglish或任何LTR语言时,它可以正常工作。

但是当它被设置为希伯来语或任何其他语言RTL时,它根本不显示。 但是,在Debug Hierarchy View中,它显示placeholder就在那里。

请注意,我使用Localizable.strings中的code而不是本地化的故事板来设置翻译。 除UITextfield占位符

外,一切正常

谢谢:)

enter image description here

编辑: 显然,所有发生的事情都是attributedPlaceholder在应用处于LTR模式时没有任何效果。 我将其中一个UITextfields背景改为白色,然后显示。只有attributedPlaceholder& NSAttributedString的颜色在RTL模式下无效

但仍然需要一个解决方案:(

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个:

extension UITextField{

    override func setLocalized() -> Void {
        if UtilityClass.isLanguageRTL()// check RTL or LTR here {
            self.textAlignment = .right
            self.semanticContentAttribute = .forceRightToLeft
        }
        else{
            self.textAlignment = .left
            self.semanticContentAttribute = .forceLeftToRight
        }
    }

}

在ViewWillAppear中

    textField1?.setLocalized()
    textField2?.setLocalized()

答案 1 :(得分:0)

我也遇到过这样的情况,即在本地化之后更改了占位符字体(不仅是LTR设置)。

我们有一个自定义对象,它继承自UITextField,并在初始化时更改颜色。

@IBInspectable
var placeholderColor: UIColor = UIColor.white {
    didSet {
        attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    ....
    attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
    ....
}

使用Localizable.strings时,我们在ViewController中翻译了字符串,如下所示。

    emailTextField.placeholder = "Generic.Textfield.Email".localized

但是,更改占位符字符串时不会触发更改占位符颜色。因此,它变为默认值(R0 G0 B 0.1 A0.22)。

我们手动override placeholder,并像初始化时一样修改attributedPlaceholder。和修复! 希望它也可以帮助其他人:)

PS:似乎是iOS 13以后的Apple修复程序,但适用于iOS 12之前的版本。