Skip to content

Instantly share code, notes, and snippets.

@JasonCanCode
Last active February 22, 2018 18:55
Show Gist options
  • Save JasonCanCode/51829d385be2ebea8a6a06f7ad0a5d5c to your computer and use it in GitHub Desktop.
Save JasonCanCode/51829d385be2ebea8a6a06f7ad0a5d5c to your computer and use it in GitHub Desktop.
In the xib IB, make the used custom view class (subclass of NibView) the File’s Owner and connect the view outlet to the xib view.
import UIKit
/**
In the xib IB, make the used custom view class (subclass of NibView)
the File’s Owner and connect the view outlet to the xib view.
*/
class NibView: UIView {
@IBOutlet weak private var view: UIView!
var nibName: String {
guard let identifier = NSStringFromClass(self.classForCoder).components(separatedBy: ".").last else {
assertionFailure("View could not be loaded from a nib. Make sure that the nib file shares the same name as the view class that is the file's owner and that the content view is mapped to owner's view IBOutlet.")
return ""
}
return identifier
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
view = initializeSubviews()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
initializeSubviews()
}
@discardableResult private func initializeSubviews() -> UIView {
let view: UIView = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)?.first as? UIView ?? UIView()
view.frame = self.bounds
addSubview(view)
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment