代码之家  ›  专栏  ›  技术社区  ›  Deepti Raghav

扩展不能包含UItextfield中存储的属性

  •  2
  • Deepti Raghav  · 技术社区  · 8 年前
    extension UITextField
    @IBInspectable var placeholdercolor: UIColor 
        {
        willSet {
             attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
        }}
    

    @IBInspectable var placeholdercolor: UIColor 
        {
    get
        {
           return self.placeholdercolor 
        }
        set
        {
            attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: placeholdercolor])
        }
    }
    

    但它在方法上给出了错误(线程1:EXC\u BAD\u ACCESS)

    get
        {
           return self.placeholdercolor 
        }
    

    请帮忙

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sweeper    8 年前
    @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])