textfield占位符居中并且也改变颜色

时间:2017-12-27 04:25:27

标签: ios swift swift4

我想将我的UITextField占位符设为center aligned并更改placeholderColor。 我已经使用this

对齐了文本中心
extension String {
    func attributedString(aligment: NSTextAlignment) -> NSAttributedString {
        return NSAttributedString(text: self, aligment: aligment)
    }
}

extension NSAttributedString {
    convenience init(text: String, aligment: NSTextAlignment) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = aligment
        self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
    }
}

并调用上面的扩展方法

textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left)

但我无法改变占位符的颜色。我该如何更改占位符颜色?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

尝试使用如下所示的修改后的扩展名。

extension NSAttributedString 
    {
        convenience init(text: String, aligment: NSTextAlignment, color:UIColor) {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = aligment
            self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor:color])
        }
    }

<强>用法

textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left, color:UIColor.red)

答案 1 :(得分:0)

只需尝试此代码

Swift 3.0

myTextField.textAlignment = .center

myTextField.attributedPlaceholder = NSAttributedString(string: "PlaceHolder", attributes: [NSForegroundColorAttributeName: UIColor.green])