我想将我的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)
但我无法改变占位符的颜色。我该如何更改占位符颜色?任何帮助表示赞赏。
答案 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])