Skip to content

Instantly share code, notes, and snippets.

@Winchariot
Last active December 3, 2017 22:35
Show Gist options
  • Save Winchariot/31ca1613d08745fa7bebfbee17284775 to your computer and use it in GitHub Desktop.
Save Winchariot/31ca1613d08745fa7bebfbee17284775 to your computer and use it in GitHub Desktop.
Instantiate and use in code a custom UIView subclass that you designed in IB
//MyView was designed in IB (xib not included in this gist)
// In IB, you need not set the file's owner, as Bundle.main.loadNibNamed() sets that for you.
// You should, however, still set its custom class on the View
import UIKit
class MyView: UIView {
class func createFromNib() -> MyView {
//loadNibNamed returns all of the top-level objects in that nib, but .first is always your UIView object
return Bundle.main.loadNibNamed("MyView", owner: self, options: nil)?.first as! MyView
}
}
//For example, if your VC contains a stack view, you may want to programmatically add to it a subview that you designed in IB
import UIKit
final class MyViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
override func viewDidLoad() {
stackView.addArrangedSubview(MyView.createFromNib())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment