Last active
August 20, 2017 10:19
-
-
Save mkral/1b04c07ff7029cc3c66e9e363e45d11d to your computer and use it in GitHub Desktop.
XIBDesignable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can really make loadViewFromNib a
private func
as it's not expected to be called outside ofxibSetup
, but other than that a great gist!