Last active
March 15, 2019 17:53
-
-
Save JasonCanCode/6a61c5cfb5f1df3bfef77c4710c08377 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Searchable { | |
/// Array of searchable properties converted to strings | |
var searchStrings: [String?] { get } | |
} | |
extension Searchable { | |
func contains(searchText: String) -> Bool { | |
let text = searchText.lowercased() | |
let searchStrings = self.searchStrings.compactMap { $0 } | |
return searchStrings.lazy.filter({ $0.lowercased().contains(text) }).first != nil | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
/** | |
A convenient way to filter your table with a search bar. | |
Example use: | |
extension MyTableViewController: SearchTableType { | |
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { | |
filterContent(for: searchText, showAllOnEmpty: true) | |
} | |
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { | |
searchBar.resignFirstResponder() | |
tableView.reloadData() | |
} | |
} | |
*/ | |
protocol SearchTableType: class, UISearchBarDelegate { | |
associatedtype T: Searchable | |
var tableView: UITableView! { get } | |
var searchBar: UISearchBar! { get } | |
var searchableItems: [T] { get } | |
var filteredItems: [T] { get set } | |
} | |
extension SearchTableType { | |
var displayItems: [Searchable] { | |
return isFiltering | |
? filteredItems | |
: searchableItems | |
} | |
var isFiltering: Bool { | |
return searchBar.isFirstResponder && !searchBarIsEmpty | |
} | |
var searchBarIsEmpty: Bool { | |
return searchBar.text?.isEmpty ?? true | |
} | |
func filterContent(for searchText: String, showAllOnEmpty: Bool = true) { | |
if showAllOnEmpty && searchText.isEmpty { | |
filteredItems = searchableItems | |
} else { | |
filteredItems = searchableItems.filter { $0.contains(searchText: searchText) } | |
} | |
tableView.reloadData() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment