Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created October 23, 2024 16:04
Show Gist options
  • Select an option

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

Select an option

Save takoikatakotako/d3f6b95383b1149bf52c1dde8c3b82d8 to your computer and use it in GitHub Desktop.
SwiftUIでSearchBar(TextField)にクリアボタンをつける
import SwiftUI
struct ContentView: View {
@State var text: String = ""
let pokemons: [String] = ["Snorlax", "Slowpoke", "Pikachu", "Eevee"]
var filterdPokemons: [String] {
if text.isEmpty {
return pokemons
} else {
return pokemons.filter {$0.uppercased().contains(text.uppercased())}
}
}
var body: some View {
ScrollView {
LazyVStack{
ZStack(alignment: .trailing) {
TextField("Type your search",text: $text)
.textFieldStyle(RoundedBorderTextFieldStyle())
if !text.isEmpty{
Button(action:
{
self.text = ""
})
{
Image(systemName: "delete.left")
.foregroundColor(Color(UIColor.opaqueSeparator))
}
.padding(.trailing, 8)
}
}
.padding(8)
ForEach(filterdPokemons, id: \.self) { pokemon in
VStack(alignment: .leading) {
Text(pokemon)
.padding(.leading, 12)
Divider()
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment