Created
January 13, 2018 14:11
-
-
Save victor-pavlychko/efbd542ef13bbfb1fc2568ac8184aac7 to your computer and use it in GitHub Desktop.
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
// | |
// 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