Avatar ·

如何使用Swift更改UITextField中placeholder文本的颜色?

大家好!我是iOS开发新手,有一个看似简单的任务却一直搞不定。

我有一个带placeholder的UITextField。默认的灰色不符合我应用的UI设计。我需要placeholder文本变成蓝色或红色。

我尝试过这样做:

textField.placeholder = "Введите имя"
textField.placeholderColor = UIColor.blue // 没有这个属性,Xcode报错

后来我在网上找到了用NSAttributedString的方法:

let placeholderText = NSAttributedString(string: "Введите имя", attributes: [NSAttributedString.Key.foregroundColor: UIColor.blue])
textField.attributedPlaceholder = placeholderText

这确实有效,但我觉得对于这么简单的任务来说太繁琐了。而且如果我有多个textField,就得为每个都写一遍。

请问有没有更简