Skip to content

Instantly share code, notes, and snippets.

@lamlv2305
Last active January 9, 2018 05:30
Show Gist options
  • Save lamlv2305/5e0371d28f717e58c2019fffa5028418 to your computer and use it in GitHub Desktop.
Save lamlv2305/5e0371d28f717e58c2019fffa5028418 to your computer and use it in GitHub Desktop.
Using xibview with storyboard. Do not forget to set "File's Owner -> Custom Class" in your xib file.
import UIKit
@IBDesignable
class XibView: UIView {
@IBInspectable var nibName: String?
private(set) var contentView: UIView?
override func awakeFromNib() {
super.awakeFromNib()
contentView = xibSetup(nibName: nibName)
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
contentView = xibSetup(nibName: nibName)
contentView?.prepareForInterfaceBuilder()
}
}
extension UIView {
func loadView(fromNib name: String) -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: name, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
func xibSetup(nibName: String?) -> UIView {
let nibName = nibName ?? String(describing: type(of: self))
guard let view = loadView(fromNib: nibName) else {
fatalError("Couldn't load nib from nibName: \(nibName)")
}
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment