While taking the iOS Developer Career Path
, I found a code fix that some of you might find helpful! Since Swift has been updated after the Codecademy course came out, some of the code in the course needs to be adjusted. Here is the TL;DR:
The section of the course I’m specifically referring to is How to present a sheet
. In the course, the presented code is:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
Text("Initial View")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
}, label {
Image(systemName: "gear")
})
}
}
.sheet(isPresented: $isPresenting) {
NavigationView {
Text("Settings Page")
}
}
}
}
}
There are a few problems I encountered.
- The location of
@State var isPresenting: Bool = false
was incorrect (earlier in the section you find
@State var isPresenting: Bool = false
NavigationView { ... }
But placing your @State var isPresenting: Bool = false
right before the navigation view was throwing an error.
- The sheet was not loading with the code as written.
After some research on substack and other online resources, I adjusted the code to this, and found everything to work smoothly in SwiftUI:
import SwiftUI
struct ContentView: View {
@State var isPresenting: Bool = false
var body: some View {
NavigationView {
Text("Initial View")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
isPresenting = true
}, label: {
Image(systemName: "gear")
})
}
}
.sheet(isPresented: $isPresenting, content: {
NavigationView {
Text("Settings Page")
}
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Hopefully this helps you, too!