2017-11-02 16 views
1
extension UITextField 
@IBInspectable var placeholdercolor: UIColor 
    { 
    willSet { 
     attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor]) 
    }} 

자리 표시 자 색상에 대한 UITextField의 Extension을 만들고 있습니다. 나는 사용자 정의 클래스를 만들려하지 않고 또한Extension에 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 
    } 

답변

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