現在SwiftUIを勉強中なので、さまざまなUIを実装しています。
今回は、SwiftUIでindexによってリストの見た目を変える実装をしてみました。
Xcode Version 14.2
EditListView.swift
struct EditListView: View {
@State private var tee = ["緑茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶",
"ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶"]
var body: some View {
VStack(spacing: 0) {
Divider().background(Color.brown).padding(.top, 10)
List {
ForEach(Array(tee.enumerated()), id: \.element) { index, tee in
if index % 2 == 0 {
VStack(alignment: .center ,spacing: 0) {
Text(tee)
.font(.system(size: 16))
.frame(maxWidth: .infinity, alignment: .leading)
}.listRowInsets(EdgeInsets())
} else {
VStack(alignment: .center ,spacing: 0) {
Text(tee)
.font(.system(size: 16))
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundColor(Color.blue)
}.listRowInsets(EdgeInsets())
}
}
}
.listStyle(PlainListStyle())
}
}
}
Array(tee.enumerated())
こちらを実装するとindexがわかるようになります。
このように黒色、青色交互のリストが出来ました。
indexによって変化させたい場合は参考にしてみてください。