Skip to content

Instantly share code, notes, and snippets.

@Aakashcs
Created July 16, 2020 00:20
Show Gist options
  • Save Aakashcs/a2846db03f923bfb545e84aebdfc1345 to your computer and use it in GitHub Desktop.
Save Aakashcs/a2846db03f923bfb545e84aebdfc1345 to your computer and use it in GitHub Desktop.
Search View with list in Swift UI
//
// SearchView.swift
// Branddose
//
// Created by Aakash on 10/07/2020.
// Copyright © 2020 Minhasoft. All rights reserved.
//
import SwiftUI
struct SearchView: View {
let array = ["Peter", "Paul", "Mary", "Anna-Lena", "George", "John", "Greg", "Thomas", "Robert", "Bernie", "Mike", "Benno", "Hugo", "Miles", "Michael", "Mikel", "Tim", "Tom", "Lottie", "Lorrie", "Barbara"]
@State private var searchText = ""
@State private var showCancelButton: Bool = false
var body: some View {
NavigationView {
VStack {
// Search view
HStack {
HStack {
Image(systemName: "magnifyingglass")
TextField("Search", text: $searchText, onEditingChanged: { isEditing in
withAnimation(.default){
self.showCancelButton = true
}
}, onCommit: {
print("onCommit")
}).foregroundColor(.primary)
Button(action: {
self.searchText = ""
}) {
Image(systemName: "xmark.circle.fill").opacity(searchText == "" ? 0 : 1)
}
}
.padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
.foregroundColor(.secondary)
.background(Color(.secondarySystemBackground))
.cornerRadius(10.0)
if showCancelButton {
Button("Cancel") {
UIApplication.shared.endEditing(true) // this must be placed before the other commands here
withAnimation(.default){
self.searchText = ""
self.showCancelButton = false
}
}
.foregroundColor(Color(.systemBlue))
}
}
.padding(.horizontal)
.navigationBarHidden(showCancelButton) // .animation(.default) // animation does not work properly
List {
// Filtered list of names
ForEach(array.filter{$0.hasPrefix(searchText) || searchText == ""}, id:\.self) {
searchText in
Text(searchText)
}
}
.navigationBarTitle(Text("Search"))
.resignKeyboardOnDragGesture()
}
}
}
}
struct SearchView_Previews: PreviewProvider {
static var previews: some View {
Group {
SearchView()
.environment(\.colorScheme, .light)
SearchView()
.environment(\.colorScheme, .dark)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment