具有优先级的Swift @IBInspectables选择它们在

时间:2018-03-20 18:52:56

标签: swift ibinspectable

我正在玩@IBInspectables。我创建了一个可重用的自定义View,它有一些@IBInspectables。

是否无法优先处理@IBInspectables被执行?

在以下情况下,修改占位符的颜色或字体。需要通过属性文本来完成。所以我需要在@IBInspectable之前执行一些@IBInspectables,比如Font,Color,它们会设置占位符文本。

在这种情况下,我已经完成了解决方法,以获得占位符Color。但是,我想在占位符中添加更多属性,比如Font,但如果我不知道它们将被执行哪个订单,我将不得不设置" attributionPlaceholder"来自修改占位符的每个IBInspectable)

@IBInspectable
var placeholder: String? {
    didSet {
        guard let placeholder = placeholder else { return }

        textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: placeholderColor ?? UIColor.red])
    }
}

@IBInspectable
var placeholderColor: UIColor? {
    didSet {
        guard let placeholderColor = placeholderColor else { return }

        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder != nil ? textField.placeholder! : "", attributes: [NSAttributedStringKey.foregroundColor: placeholderColor])
    }
}

1 个答案:

答案 0 :(得分:3)

你应该以呼叫顺序无关紧要的方式编写设置者。这不仅仅是关于Interface Builder中调用的顺序,这也是关于以编程方式调用的顺序。

你打电话是不是无关紧要:

view.placeholder = 
view.placeholderColor = 

view.placeholderColor = 
view.placeholder = 

示例实施:

@IBInspectable
var placeholder: String? {
   didSet {
      updatePlaceholder()
   }
}

@IBInspectable
var placeholderColor: UIColor? {
   didSet {
      updatePlaceholder()
   }
}

private func updatePlaceholder() {
   textField.attributedPlaceholder = NSAttributedString(
       string: placeholder ?? "",
       attributes: [.foregroundColor: placeholderColor ?? UIColor.red]
   )
}
相关问题