Skip to content

Instantly share code, notes, and snippets.

@karnlund
Last active June 1, 2018 16:20
Show Gist options
  • Save karnlund/b666acc88532d5f1ca591dd3580605cc to your computer and use it in GitHub Desktop.
Save karnlund/b666acc88532d5f1ca591dd3580605cc to your computer and use it in GitHub Desktop.
This is fromNib methods converted for Swift 3. This is obtained from StackOverflow here http://stackoverflow.com/questions/24857986/load-a-uiview-from-nib-in-swift
// This came from StackOverflow
// http://stackoverflow.com/questions/24857986/load-a-uiview-from-nib-in-swift
//
// https://gist.github.com/karnlund/b666acc88532d5f1ca591dd3580605cc
import UIKit
public extension UIView {
public class func fromNib(_ nibName: String? = nil) -> Self? {
return loadFromNib(nibName)
}
public class func loadFromNib<T : UIView>(_ nibName: String? = nil) -> T? {
var view: T?
let name: String
if let nibName = nibName {
name = nibName
} else {
// Most nibs are demangled by practice, if not, just declare string explicitly
name = self.nibName
}
if let nibViews = Bundle.main.loadNibNamed(name, owner: self, options: nil) {
for nibView in nibViews {
if let tog = nibView as? T {
view = tog
break
}
}
return view
}
return nil
}
public class var nibName: String {
let name = String(describing: self)
return name
}
public class var nib: UINib? {
if let _ = Bundle.main.path(forResource: nibName, ofType: "nib") {
return UINib(nibName: nibName, bundle: nil)
} else {
return nil
}
}
}
@karnlund
Copy link
Author

This works wonderfully.

Note: if you have subclasses you need to make sure you call fromNib on exactly the class you want to create from the nib file.

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