extension UITextField
@IBInspectable var placeholdercolor: UIColor
{
willSet {
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}}
I am creating extension for UITextField for placeholder colour . I don't want to create custom class and I also try
@IBInspectable var placeholdercolor: UIColor
{
get
{
return self.placeholdercolor
}
set
{
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
}
}
but it is giving error (Thread 1: EXC_BAD_ACCESS) on method
get
{
return self.placeholdercolor
}
please help
@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])
}
}
What you should instead in the getter is return the foreground color attribute in the attributed string:
get
{
return attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor
}
I suggest you make this property an optional just in case the property is not set.
EDIT:
Your setter is also incorrect. You should use newValue
:
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue])