Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created October 24, 2024 01:32
Show Gist options
  • Select an option

  • Save takoikatakotako/ac6817e194c183f2dd66e2a1234420fb to your computer and use it in GitHub Desktop.

Select an option

Save takoikatakotako/ac6817e194c183f2dd66e2a1234420fb to your computer and use it in GitHub Desktop.
SwiftUIでリストのセルをタップしてアラートを表示させる
import SwiftUI
struct ContentView: View {
@State var showingAlert = false
@State var pokemon: Pokemon?
let pokemons: [Pokemon] = [
Pokemon(id: 143, name: "Snorlax"),
Pokemon(id: 25, name: "Pikachu"),
Pokemon(id: 138, name: "Psyduck"),
Pokemon(id: 9, name: "Blastoise"),
Pokemon(id: 79, name: "Slowpoke")]
var body: some View {
List(pokemons) { pokemon in
Button {
self.pokemon = pokemon
showingAlert = true
} label: {
Text(pokemon.name)
}
}
.alert("Alert", isPresented: $showingAlert, presenting: pokemon) { pokemon in
Button(pokemon.name, role: .none) {
print("Close")
}
} message: { pokemon in
Text(pokemon.name)
}
}
}
#Preview {
ContentView()
}
import Foundation
struct Pokemon: Identifiable {
let id: Int
let name: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment