Skip to content

Instantly share code, notes, and snippets.

@Streebor
Created July 9, 2018 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Streebor/d0c91058dd03cbb400abd158779c35ba to your computer and use it in GitHub Desktop.
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
//
// 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