Skip to content

Instantly share code, notes, and snippets.

@sushant-here
Last active September 28, 2018 00:11
Show Gist options
  • Save sushant-here/03158d67ab4803b0ad81e2047bf25ed1 to your computer and use it in GitHub Desktop.
Save sushant-here/03158d67ab4803b0ad81e2047bf25ed1 to your computer and use it in GitHub Desktop.
Load UI view from XIB file for use in storyboard with IBDesignable
//
// SVDesignableXibView.swift
// crypto
//
// Created by Sushant Verma on 29/1/18.
// Copyright © 2018 Sushant Verma. All rights reserved.
//
import UIKit
@IBDesignable
class SVDesignableXibView: UIControl {
//SEE: https://stackoverflow.com/questions/30335089/reuse-a-uiview-xib-in-storyboard/37668821#37668821
var contentView : UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView.frame = bounds
// Make the view stretch with containing view
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: 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