1
2

More than 1 year has passed since last update.

SwiftUIでindexによってリストの見た目を変える実装方法

Posted at

現在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())
        }
    }
}

スクリーンショット 2023-07-30 10.25.53.png

Array(tee.enumerated())
こちらを実装するとindexがわかるようになります。
このように黒色、青色交互のリストが出来ました。
indexによって変化させたい場合は参考にしてみてください。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2