LoginSignup
1
1

More than 1 year has passed since last update.

[SwiftUI] Picker 内の ForEach で id: \.self した時のバグ

Posted at

selection が index の値になってしまいます。

スクリーンショット 2021-07-26 午後4.21.12.png

struct MyView: View {
    @State var selection = 10
    let items = [10,20,30]

    var body: some View {
        VStack {
            Text("selection: \(selection)")
            Picker(selection: $selection, label: Text("")) {
                ForEach(0..<items.count, id: \.self) { index in
                    Text("\(items[index])")
                        .tag(items[index])
                }
            }
        }
    }
}

下の様に、IdentifiableなものをForEachすれば直りました。

スクリーンショット 2021-07-26 午後4.28.00.png

struct MyView: View {
    @State var selection = 10

    struct Item: Identifiable {
        var id = UUID()
        var num:Int
        init(_ num: Int) { self.num = num }
    }
    let items = [Item(10), Item(20), Item(30)]

    var body: some View {
        VStack {
            Text("selection: \(selection)")
            Picker(selection: $selection, label: Text("")) {
                ForEach(items) { item in
                    Text("\(item.num)")
                        .tag(item.num)
                }
            }
        }
    }
}

バージョン
Swift 5.4

1
1
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
1