Let’s modify the UI by adding a Sidebar and showing images in our list.
Goals
- Improve navigation
- Beautify app
- Clarify navigation
Steps
- Use Pod.recent request
- Add
SidebarView
- Replace List
Text
with ourPodDetailView
- Move app structure to
ContentView
- Change
List
toSection
in PodDetailView - Switch on pods
- Split our list view into
loadingView
andlistView
- Set the environment for our
Content
andSidebarView
previews
struct SideBarView: View {
var body: some View {
List {
NavigationLink {
PodListView()
} label: {
Label("Recents", systemImage: "clock")
}
}
}
}
ContentView
struct ContentView: View {
var body: some View {
NavigationView {
SidebarView()
PodListView()
}
}
}
PodDetailView
List
to Section
PodListView
struct PodListView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(fetchRequest: Pod.recent, animation: .default)
var pods: FetchedResults<Pod>
var body: some View {
switch pods {
case nil: loadingView
default: listView
}
}
var loadingView: some View {
Text("Fetching Pods...")
.task {
if pods.isEmpty { await getMore() }
}
}
var listView: some View {
List {
ForEach(pods, id: \.id) { pod in
PodDetailView(pod: pod)
}
Section {
Button("GET More") { Task { await getMore() } }
}
}
.navigationBarTitleDisplayMode(.inline)
.refreshable {
await getNew()
}
}
}
Previews
Be sure to Set the environment value for our ContentView
and SideBarView
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
struct SidebarView_Previews: PreviewProvider {
static var previews: some View {
// Wrapping it with a NavigationView enables the expected behavior in Canvas
NavigationView {
SidebarView()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
}
Watch the YouTube series and checkout the github repo.