Skip to content

Instantly share code, notes, and snippets.

@victor-pavlychko
Created January 13, 2018 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victor-pavlychko/efbd542ef13bbfb1fc2568ac8184aac7 to your computer and use it in GitHub Desktop.
Save victor-pavlychko/efbd542ef13bbfb1fc2568ac8184aac7 to your computer and use it in GitHub Desktop.
//
// XibView.swift
// XibView
//
// Created by Victor Pavlychko on 1/13/18.
//
import UIKit
@IBDesignable
open class XibView: UIView {
@IBOutlet open var contentView: UIView? {
didSet {
guard contentView != oldValue, let contentView = contentView else {
return
}
oldValue?.removeFromSuperview()
contentView.translatesAutoresizingMaskIntoConstraints = true
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.frame = bounds
addSubview(contentView)
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
instantiateNib(findNib())
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
instantiateNib(findNib())
}
private func findNib() -> (Bundle, String) {
let superclasses = sequence(first: type(of: self) as AnyClass, next: { return $0.superclass() })
for cls in superclasses {
let bundle = Bundle(for: cls)
let name = String(describing: cls).components(separatedBy: ".").last ?? ""
if bundle.url(forResource: name, withExtension: "nib") != nil {
return (bundle, name)
}
}
fatalError("Couldn't find nib for \(type(of: self))")
}
private func instantiateNib(_ nib: (bundle: Bundle, name: String)) {
nib.bundle.loadNibNamed(nib.name, owner: self, options: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment