Search code examples
swiftuiviewswift-extensions

UIView extension with optional properties


Here's my code right now:

@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'

My question is how do I extend UIView to include the optional header and footer variables? Maybe I'm doing this completely wrong in which case I'd appreciate a pointer in the right direction.


Solution

  • If I understand your question correctly, You need to make your BaseView a subclass of UIView. Then in your class definition, you can add optional properties as you like. The code will look something like this

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

    EDIT

    Based on your explanation in the comments, I believe you need something like this

    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'