SwiftUIのListでSpacerの部分にもタップ判定をつける


SwiftUIのListでSpacerの部分にもタップ判定をつける方法です。 .contentShape(Rectangle()) を設定することでタップ範囲を広げています。

ListでSpacerの部分にもタップ判定をつける

参考サイト SwiftUI pick a value from a list with ontap gesture

ContentView.swift

import SwiftUI

struct ContentView: View {
    let pokemons: [String] = ["Snorlax", "Pikachu", "Slowpoke"]
    var body: some View {
        List(pokemons, id: \.self) {pokemon in
            HStack {
                Text(pokemon)
                Spacer()
            }
            .contentShape(Rectangle())
            .onTapGesture {
                print(pokemon)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}