Last active
May 1, 2020 10:01
-
-
Save lamprosg/86f7707f3013f6a752709da910f4ae32 to your computer and use it in GitHub Desktop.
(iOS) Override loadView()
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
//https://swiftrocks.com/writing-cleaner-view-code-by-overriding-loadview.html | |
/// The HasCustomView protocol defines a customView property for UIViewControllers to be used in exchange of the regular view property. | |
/// In order for this to work, you have to provide a custom view to your UIViewController at the loadView() method. | |
public protocol HasCustomView { | |
associatedtype CustomView: UIView | |
} | |
extension HasCustomView where Self: UIViewController { | |
/// The UIViewController's custom view. | |
public var customView: CustomView { | |
guard let customView = view as? CustomView else { | |
fatalError("Expected view to be of type \(CustomView.self) but got \(type(of: view)) instead") | |
} | |
return customView | |
} | |
} | |
final class MyViewController: UIViewController, HasCustomView { | |
typealias CustomView = MyView // <- Declare the type of your view so you don't have to cast it all the time | |
override func loadView() { | |
let customView = CustomView() | |
customView.delegate = self | |
view = customView | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
customView.render() //some MyView method | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment