Last active
December 3, 2017 22:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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