我创建了一个自定义 UITextField
,其中覆盖了 placeholder
属性。每当将值写入 placeholder
属性时,都会创建一个 NSAttributedString
并将其分配给 attributedPlaceholder
。
自定义类的代码如下-
class CustomTextField: UITextField {
override var placeholder: String? {
get {
return attributedPlaceholder?.string
}
set {
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.green]
attributedPlaceholder = NSAttributedString(string: newValue ?? "", attributes: attributes)
}
}
}
我在 Storyboard中创建了一个 UITextField
并将其自定义类指定为 CustomTextField
。我将 Storyboard中的“Placeholder”属性设置为某个值。
当应用程序运行时,占位符显示为灰色,而不是预期的绿色。
任何人都可以指出为什么应用程序运行时不显示 attributedPlaceholder
吗?
最佳答案
你在这里
extension CustomTextField {
@IBInspectable var placeholderColor: UIColor? {
get {
return self.placeholderColor
}
set {
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [.foregroundColor: newValue!])
}
}
}
您可以通过 Storyboard或代码访问占位符颜色 希望对您有所帮助
关于ios - 具有覆盖占位符的自定义 UITextField 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359922/