-
Notifications
You must be signed in to change notification settings - Fork 912
/
SearchResultsController.swift
65 lines (54 loc) · 2.34 KB
/
SearchResultsController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import UIKit
class SearchResultsController : UITableViewController {
var originalData = [String]()
var filteredData = [String]()
weak var searchController : UISearchController?
func take(data:[[String]]) {
// we don't use sections, so flatten the data into a single array of strings
self.originalData = data.flatMap{$0}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
// we are now in total charge of the interface...
// ... so make room for the tall search bar
self.tableView.contentInset = UIEdgeInsetsMake(90, 0, 0, 0)
self.tableView.scrollIndicatorInsets = self.tableView.contentInset
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath)
cell.textLabel!.text = self.filteredData[indexPath.row]
return cell
}
}
extension SearchResultsController : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
print("update")
self.searchController = searchController // keep a weak ref just in case
let sb = searchController.searchBar
let target = sb.text!
self.filteredData = self.originalData.filter {
s in
var options = String.CompareOptions.caseInsensitive
// we now have scope buttons; 0 means "starts with"
if searchController.searchBar.selectedScopeButtonIndex == 0 {
_ = options.insert(.anchored) // bug?
}
let found = s.range(of:target, options: options)
return (found != nil)
}
self.tableView.reloadData()
}
}
extension SearchResultsController : UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
print("button")
self.updateSearchResults(for:self.searchController!)
}
}