Last active
September 28, 2018 00:11
-
-
Save squeaky-nose/03158d67ab4803b0ad81e2047bf25ed1 to your computer and use it in GitHub Desktop.
Load UI view from XIB file for use in storyboard with IBDesignable
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
// | |
// 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