I have a list with five rows as follows.
import SwiftUI
struct ContentView: View {
@State var horizonModels = [MenuModel]()
var body: some View {
ZStack {
Color.green
NavigationView {
List {
ForEach(horizonModels, id: \.self) { model in
if model.id == 0 {
NavigationLink(
destination: MenuView0(),
label: {
Text("\(model.name)")
})
} else {
NavigationLink(
destination: MenuView1(),
label: {
Text("\(model.name)")
})
}
}
}
}
}
.ignoresSafeArea()
.onAppear(perform: {
horizonModels = [
MenuModel.init(id: 0, name: "Shopping"),
MenuModel.init(id: 1, name: "Gift cards"),
MenuModel.init(id: 2, name: "Video"),
MenuModel.init(id: 3, name: "Music"),
MenuModel.init(id: 4, name: "Account")
]
})
}
}
struct MenuModel: Hashable, Identifiable {
let id: Int
let name: String
}
struct MenuView0: View {
var body: some View {
Text("Menu 0")
}
}
struct MenuView1: View {
var body: some View {
Text("Menu 1")
}
}
And I get something like the following screenshot.
Well, I actually want to create a horizontal list like the screenshot below. I could do it except that I am not able to use NavigationView and NavigationLink instead of ScrollView and HStack. So how can I make a horizontally-scrollable list with NavigationView and NavigationLink?
Muchos thankos.
I've solved the problem by having NavigationView before ScrollView like the following.
ZStack {
VStack {
NavigationView {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(horizonModels, id: \.self) { model in
if model.id == 0 {
NavigationLink(model.name) {
MenuView0()
}
.font(.system(size: 20.0))
.padding(.horizontal, 20.0)
.foregroundColor(Color.white)
} else {
NavigationLink(model.name) {
MenuView1()
}
.font(.system(size: 20.0))
.padding(.horizontal, 20.0)
.foregroundColor(Color.white)
}
}
}
}
.frame(height: 40.0)
.background(Color.orange)
}
}
}
That's kind of odd to me.