Swift @IBInspectables 优先选择它们执行的顺序

Swift @IBInspectables with priority choose the order are they executed in

我正在玩@IBInspectables。我创建了一个可重用的自定义视图,其中包含一些 @IBInspectables。

有没有办法让@IBInspectables优先执行?

在下面的例子中,修改占位符的颜色或字体需要通过属性文本来完成。所以我需要在设置占位符文本的@IBInspectable 之前执行一些@IBInspectables,如Font、Color。

在这种情况下,我已经完成了始终获得占位符颜色的解决方法。但是,我想向占位符添加更多属性,如字体,但如果我不知道它们将执行哪个顺序,我将不得不从每个修改占位符的 IBInspectable 中设置 "attributedPlaceholder")

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

您应该以调用顺序无关紧要的方式编写 setter。这不仅与 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]
   )
}