21 Build a View

Text Components

Text(String(format: "Heel: %.1f", heel))

works, but

Text("Heel: \(heel, specifier: "%.1f")")

is tidier for displaying formatted text in SwiftUI. In a rather confusing turnabout, the specifier format doesn’t work in ordinary Swift executable code

Bindings

Passing an @State variable directly to a child view with $ and @Binding will let the child change the parent’s state. Mapper provides an example of building more general bindings in SettingsView.swift, showing how the set: method can propagate the result to multiple dependent variables.

Navigation

ContentView.swift in the Mapper app provides an example of how to use a NavigationView() to work down into subsidiary window views. Most of those views simply return via the back button at the top left, but PickSpotView.swift uses this code to return up a level after a selection button is pushed.

@Environment(.presentationMode) var presentation   // needed to go back a level
self.presentation.wrappedValue.dismiss()    // go back a level

Data Types

String v String? v String! types

The following ? (optional) means the variable might be nil and needs to be unwrapped. The following ! (implicitly unwrapped optional) means the variable might be nil, but let the app crash if it is — avoid them. The coalescing operator ?? allows you to supply a default to be used if the variable is nil (unassigned). This turns an unreliable optional value into a reliable unwrapped value with code like:

var unwrappedValue = optionalValue ?? defaultValue

The if let else structure provides a way to see if an optional exists and choose what code to run as a result.

if let a = b.val {
 } else {  } 

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Rick's Remote and Online Teaching Notes Copyright © 2019 by Rick Sellens is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book