这是我的 UITextField
子类的简化版本:
class MyTextField: UITextField {
override func drawPlaceholder(in rect: CGRect) {
if let placeholder = self.placeholder {
print(placeholder) // -> prints the value
let attributes = [NSForegroundColorAttributeName: UIColor.red]
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
}
}
}
在 IB 中,文本字段分配给了我的子类,但无论我将其设置为“Plain”还是“Attributed”、字体、颜色等都没有关系。我确实给它一个初始占位符值,但是当我运行应用程序它只是空白。有什么建议吗?
最佳答案
您正在覆盖 drawPlaceholder
方法而不是调用 super
。并且您的替换代码不会尝试实际绘制占位符文本。因此占位符永远不会出现。
为什么不覆盖 placeholder
属性的 setter,以便它根据需要设置 attributedPlaceholder
。然后你不需要覆盖 drawPlaceholder
一切都会工作。
关于ios - 无法在子类 UITextField 中设置属性占位符的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907459/