Skip to content

Instantly share code, notes, and snippets.

@aibobrov
Created September 17, 2018 14:05
Show Gist options
  • Save aibobrov/499ea7427efe747e4e4c9c6ee39c94c8 to your computer and use it in GitHub Desktop.
Save aibobrov/499ea7427efe747e4e4c9c6ee39c94c8 to your computer and use it in GitHub Desktop.
Subclass of UIView for comfort creating custom views from Xib
import UIKit
/*
Usage:
1. Create new xib file.
2. Create new swift file containg class subclassed from CustomXibView.
3. In xib set recently created class name as File's owner.
*/
@IBDesignable
class CustomXibView: UIView {
var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
// MARK: - Nib handlers
private func xibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(contentView)
insertSubview(contentView, at: 0)
}
private func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
xibSetup()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment