Skip to content

Instantly share code, notes, and snippets.

@mkj-is
Last active October 13, 2020 10:20
Show Gist options
  • Save mkj-is/15ece603186f416c8a288d9a674464f2 to your computer and use it in GitHub Desktop.
Save mkj-is/15ece603186f416c8a288d9a674464f2 to your computer and use it in GitHub Desktop.
Simple Nibable protocol for simple initialization of views from nib
//
// Nibable.swift
//
// Created by Matěj Kašpar Jirásek on 12/08/16.
// Copyright © 2016 Matěj Kašpar Jirásek. All rights reserved.
//
import UIKit
protocol Nibable {
static var nibName: String { get }
}
extension Nibable where Self: UIView {
static var nibName: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
static var nib: UINib {
return UINib(nibName: Self.nibName, bundle: nil)
}
init(owner: AnyObject? = nil) {
let views = Self.nib.instantiate(withOwner: owner, options: [:])
for view in views {
if let view = view as? Self {
self = view
return
}
}
fatalError("Nib for class \(Self.nibName) could not be loaded!")
}
}
@mkj-is
Copy link
Author

mkj-is commented Aug 12, 2016

This protocol extension allows us to simply initialize your custom views from nib, the only thing you need is that your custom view class conforms to the Nibable protocol and the nib must have same name as the custom class. Then you can initialize your view simply for example like this: YourView(owner: self)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment