swift 文本域占位符居中并更改颜色

vsaztqbk  于 2023-02-21  发布在  Swift
关注(0)|答案(2)|浏览(150)

我想将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)

但是我不能改变占位符的颜色。我应该如何改变我的占位符颜色?任何帮助都是感激的。

l7wslrjt

l7wslrjt1#

尝试使用修改后的扩展如下..

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)
mbzjlibv

mbzjlibv2#

简单地试试这个代码
雨燕3.0

myTextField.textAlignment = .center

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

相关问题