Skip to content

Instantly share code, notes, and snippets.

@icanswiftabit
Last active June 27, 2016 14:52
Show Gist options
  • Save icanswiftabit/1ec1158f8e195874ec4766d556bac2f3 to your computer and use it in GitHub Desktop.
Save icanswiftabit/1ec1158f8e195874ec4766d556bac2f3 to your computer and use it in GitHub Desktop.
How to create and use reusable UIView.
  1. After creating CustomView.Swift & CustomView.xib in CustomView.xib as Class in File's Owner position set CustomView
  2. Then add func commonInit to init(frame:) and init(aCoder:) and you're ready to go.

CustomView.Swift

class CustomView : UIView {
    @IBOutlet weak private var contentView:UIView!
    // other outlets
    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        self.commonInit()
    }
    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        self.commonInit()
    }
    private func commonInit() {
        NSBundle.mainBundle().loadNibNamed(String(self.dynamicType).componentsSeparatedByString("__").last!, owner: self, options: nil)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [FlexibleHeight, .FlexibleWidth]
        self.addSubview(contentView)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment