扩展可能不包含 UItextfield 中的存储属性
Extensions may not contain stored properties in UItextfield
extension UITextField
@IBInspectable var placeholdercolor: UIColor
{
willSet {
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}}
我正在为占位符颜色的 UITextField 创建扩展。我不想创建自定义 class,我也尝试
@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
}
请帮忙
@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 中改为 return 属性字符串中的前景色属性:
get
{
return attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor
}
我建议您将此 属性 设为可选,以防未设置 属性。
编辑:
您的setter也不正确。你应该使用 newValue
:
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue])
extension UITextField
@IBInspectable var placeholdercolor: UIColor
{
willSet {
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}}
我正在为占位符颜色的 UITextField 创建扩展。我不想创建自定义 class,我也尝试
@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
}
请帮忙
@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 中改为 return 属性字符串中的前景色属性:
get
{
return attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor
}
我建议您将此 属性 设为可选,以防未设置 属性。
编辑:
您的setter也不正确。你应该使用 newValue
:
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue])