ViewController's for SwiftUI.
The core idea is that the ViewController
is owning, or at least driving,
the View(s). Not the other way around.
Blog entry explaining all the things: Model View Controller for SwiftUI
Just the basics to get started quickly.
- create a SwiftUI project in Xcode (iOS is tested better)
- add the
ViewController
package, e.g. viagit@github.com:ZeeZide/ViewController.git
- create a new RootViewController, e.g.
HomePage.swift
:import ViewController class HomePage: ViewController { var view: some View { VStack { Text("Welcome to MWC!") .font(.title) .padding() Spacer() } } }
- Instantiate that in the scene view, the
ContentView.swift
generated by Xcode:import ViewController struct ContentView: View { var body: some View { MainViewController(HomePage()) } }
- Compile and Run, should show the HomePage
- create a new ViewController, e.g.
Settings.swift
:import ViewController class Settings: ViewController { var view: some View { // the View being controlled VStack { Text("Welcome to Settings!") .font(.title) .padding() Spacer() } } }
- Add an action to present the
Settings
from theHomePage
:import ViewController class HomePage: ViewController { func configureApp() { show(Settings()) // or `present(Settings())` } var view: some View { VStack { Text("Welcome to MWC!") .font(.title) .padding() Divider() Button(action: self.configureApp) { Label("Configure", systemImage: "gear") } Spacer() } } }
Pressing the button should show the settings in a sheet.
- Wrap the HomePage in a
NavigationController
, in the scene view:import ViewController struct ContentView: View { var body: some View { MainViewController(NavigationController(rootViewController: HomePage())) } }
Note pressing the button does a navigation. Things like this should also work:
func presentInSheet() {
let vc = SettingsPage()
vc.modalPresentationStyle = .sheet
present(vc)
}
The presentations so far make use of a hidden link. To explicitly
inline a NavigationLink
, use PushLink
, which wraps that.
- Add a
PushLink
(until I get anNavigationLink
init extension working) to present theSettings
from theHomePage
:import ViewController class HomePage: ViewController { var view: some View { VStack { Text("Welcome to MWC!") .font(.title) .padding() Divider() PushLink("Open Settings", to: Settings()) Spacer() } } }
ViewController is brought to you by ZeeZide. We like feedback, GitHub stars, cool contract work, presumably any form of praise you can think of.
Want to support my work? Buy an app: Past for iChat, SVG Shaper, Shrugs, HMScriptEditor. You don't have to use it! 😀