Last active
October 17, 2016 19:19
-
-
Save gravicle/f21429a2be96b4da6663dac65d6fd84e to your computer and use it in GitHub Desktop.
Abstract class allowing UIViews to be programmatically initialized while using IB internally for layout
This file contains 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
import UIKit | |
/// Allows loading view from Nibs named the same as the class. | |
class IBLoadableView: UIView { | |
fileprivate var view: UIView! | |
convenience init() { | |
self.init(frame: CGRect.zero) | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
xibSetup() | |
setup() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
xibSetup() | |
setup() | |
} | |
} | |
// MARK: - Setup | |
extension IBLoadableView { | |
/// Any setup after initiaization can be done here. Always call super at some point. | |
func setup() { | |
backgroundColor = .clear | |
} | |
} | |
// MARK: - XIB Loading | |
fileprivate extension IBLoadableView { | |
func xibSetup() { | |
view = loadViewFromNib(named: nameOfClass) | |
addSubview(view) | |
view.layoutWithEdgesEqualToSuperView() | |
awakeFromNib() | |
} | |
func loadViewFromNib(named name: String) -> UIView { | |
let bundle = Bundle(for: type(of: self)) | |
if nibExists(withName: name, in: bundle) { | |
let nib = UINib(nibName: name, bundle: bundle) | |
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView | |
return view | |
} else if let superclass = superclass { | |
return loadViewFromNib(named: superclass.nameOfClass) | |
} else { | |
fatalError("No NIB found: \(nameOfClass)") | |
} | |
} | |
func nibExists(withName name: String, in bundle: Bundle) -> Bool { | |
return bundle.path(forResource: name, ofType: "nib") != nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment