Skip to content

Instantly share code, notes, and snippets.

@Winchariot
Last active December 3, 2017 22:34
Show Gist options
  • Save Winchariot/d4757572e28ae0bd9c8e9980dbf75d2e to your computer and use it in GitHub Desktop.
Save Winchariot/d4757572e28ae0bd9c8e9980dbf75d2e to your computer and use it in GitHub Desktop.
Use a custom UIView that you designed in IB as a building block in another ViewController
//This is a valuable method to accomplish the following:
// You designed your view, MyView, in IB in its own .xib
// You have a VC, MyViewController, on which you want to lay out 1 or more MyView elements
//Here are the steps to follow after your view + VC have been laid out:
// In IB on MyViewController, lay out a placeholder View and set its custom class to MyView
// In IB on MyView, ensure the file's owner is set to MyView
// (It then becomes unnecessary to set the custom class on MyView in IB. Let it think it's just a UIView)
import UIKit
class MyView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let nib = UINib(nibName: "MyView", bundle: Bundle.main)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
view.frame = bounds
insertSubview(view, at: 0)
}
}
//No further code is required in your VC! Just drag your outlet to your MyView(s) and use them as normal
import UIKit
final class MyViewController: UIViewController {
@IBOutlet weak var view: MyView!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment