extension UITextField
@IBInspectable var placeholdercolor: UIColor
{
willSet {
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}}
我正在为UITextField创建占位符颜色的扩展名。我不想创建自定义类,我也尝试
@IBInspectable var placeholdercolor: UIColor
{
get
{
return self.placeholdercolor
}
set
{
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}
}
但它在方法
上给出了错误(线程1:EXC_BAD_ACCESS)get
{
return self.placeholdercolor
}
请帮助
答案 0 :(得分:1)
@IBInspectable var placeholdercolor: UIColor
{
get
{ // you can't return this here because this will call the getter again and again -> Stack Overflow
return self.placeholdercolor
}
set
{
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}
}
你应该在getter中代替的是返回属性字符串中的前景色属性:
get
{
return attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor
}
我建议您将此属性设置为可选,以防未设置该属性。
编辑:
你的二传手也不正确。您应该使用newValue
:
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue])