带有可选属性的UIView扩展

时间:2017-07-21 06:32:38

标签: swift uiview swift-extensions

这是我现在的代码:

@objc protocol BaseView {
  @objc optional var header: UILabel { get set }
  @objc optional var footer: UILabel { get set }
}

class ViewWithHeader: UIView, BaseView {
  @IBOutlet var header: UILabel!
}

class ViewWithFooter: UIView, BaseView {
  @IBOutlet var footer: UILabel!
}


var view: BaseView!
if (header != nil) {
  view = Bundle.main.loadNibNamed("ViewWithHeader", owner: self, option: nil)?.first as! ViewWithHeader
} else if (footer != nill) {
  view = Bundle.main.loadNibNamed("ViewWithFooter", owner: self, option: nil)?.first as! ViewWithFooter
}

view.header?.text = "Header"
view.footer?.text = "Footer"
view.alpha // This line fails because BaseView has no member 'alpha'

我的问题是如何扩展UIView以包含可选的headerfooter变量?也许我这样做完全错了,在这种情况下,我会欣赏指向正确方向的指针。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您需要将BaseView作为UIView的子类。然后在类定义中,您可以根据需要添加可选属性。代码看起来像这样

class BaseView: UIView {
    var header: UILabel?
    var footer: UILabel?
}

修改

根据你在评论中的解释,我相信你需要这样的东西

class BaseView: UIView {
    @IBOutlet var header: UILabel?
    @IBOutlet var footer: UILabel?
}

class ViewWithHeader: BaseView {
}

class ViewWithFooter: BaseView {
}


var view: BaseView!
if (header != nil) {
  view = Bundle.main.loadNibNamed("ViewWithHeader", owner: self, option: nil)?.first as! ViewWithHeader
} else if (footer != nil) {
  view = Bundle.main.loadNibNamed("ViewWithFooter", owner: self, option: nil)?.first as! ViewWithFooter
}

view.header?.text = "Header"
view.footer?.text = "Footer"
view.alpha // This line fails because BaseView has no member 'alpha'