2
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

Dennis Vennink
  • 1,083
  • 1
  • 7
  • 23
Deepti Raghav
  • 852
  • 1
  • 9
  • 26

1 Answers1

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])
    }
}

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])
Sweeper
  • 213,210
  • 22
  • 193
  • 313