Created
July 9, 2018 13:31
-
-
Save Streebor/d0c91058dd03cbb400abd158779c35ba to your computer and use it in GitHub Desktop.
Swift base class that auto loads xib with the same name from bundle
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
// | |
// NibView.swift | |
// | |
// Created by Stefan Vasiljevic on 2018-07-07. | |
// Copyright © 2018 Stefan Vasiljevic. All rights reserved. | |
// | |
import UIKit | |
@IBDesignable | |
class NibView: UIView { | |
weak var view: UIView! | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
// Setup view from .xib file | |
xibSetup() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
// Setup view from .xib file | |
xibSetup() | |
} | |
private func xibSetup() { | |
self.backgroundColor = UIColor.clear | |
let nibView = self.loadNib() | |
self.view = nibView | |
nibView.translatesAutoresizingMaskIntoConstraints = false | |
nibView.frame = bounds | |
self.addSubview(nibView) | |
NSLayoutConstraint.activate([ | |
self.topAnchor.constraint(equalTo: nibView.topAnchor), | |
self.bottomAnchor.constraint(equalTo: nibView.bottomAnchor), | |
self.leadingAnchor.constraint(equalTo: nibView.leadingAnchor), | |
self.trailingAnchor.constraint(equalTo: nibView.trailingAnchor)]) | |
} | |
/// Loads instance from nib with the same name. | |
func loadNib() -> UIView { | |
let bundle = Bundle(for: type(of: self)) | |
let nibName = type(of: self).description().components(separatedBy: ".").last! | |
let nib = UINib(nibName: nibName, bundle: bundle) | |
return nib.instantiate(withOwner: self, options: nil).first as! UIView | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment