Skip to content

Instantly share code, notes, and snippets.

@mkral
Last active August 20, 2017 10:19
Show Gist options
  • Save mkral/1b04c07ff7029cc3c66e9e363e45d11d to your computer and use it in GitHub Desktop.
Save mkral/1b04c07ff7029cc3c66e9e363e45d11d to your computer and use it in GitHub Desktop.
XIBDesignable
//
// XIBDesignable.swift
//
// Created by Michael Kral on 8/15/17.
//
import UIKit
protocol XIBDesignable {
func xibSetup()
}
extension XIBDesignable where Self: UIView {
func xibSetup(){
let view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: Self.self), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
@gligorkot
Copy link

You can really make loadViewFromNib a private func as it's not expected to be called outside of xibSetup, but other than that a great gist!

@mkral
Copy link
Author

mkral commented Aug 16, 2017

@gligorkot, just fixed it. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment