Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active May 9, 2018 17:30
Show Gist options
  • Save IanKeen/0a690db6a68958e62fd5 to your computer and use it in GitHub Desktop.
Save IanKeen/0a690db6a68958e62fd5 to your computer and use it in GitHub Desktop.
Class to allow you to use NIB BASED custom UIView in interface builder
import UIKit
open class NibLoadableView: UIView {
//MARK: - Public Properties
private(set) var customView: UIView!
//MARK: - Lifecycle
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.nibSetup()
self.initialSetup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.nibSetup()
self.initialSetup()
}
//MARK: - Private
private func nibSetup() {
customView = loadViewFromNib()
customView.frame = bounds
customView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(customView)
}
private func loadViewFromNib() -> UIView {
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView
}
//MARK: - Override Points
open func initialSetup() { }
open var nibName: String { return String(describing: self) }
open var bundle: Bundle { return .main }
}
//NOTE: By default the .xib has the same name as the class
// in this instance MyView.xib
// To use it in interface builder simply add a `UIView` and change its class to `MyView`
//
// To use a different .xib, override `nibName`
class MyView: NibLoadableView {
@IBOutlet private var someLabel: UILabel!
@IBOutlet private var someButon: UIButton!
override func initialSetup() {
//do one time setup stuff here
self.backgroundColor = .redColor()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment