Search implementation with tableView iOS swift
Solution:
First you have to create two arrays for the implementation. One array for initially fetch and save all the data.
Second one for searched filtered data.
When the user clicks the search button then clear the dataArray and filter from main array.
The class will be like below.
First you have to create two arrays for the implementation. One array for initially fetch and save all the data.
Second one for searched filtered data.
When the user clicks the search button then clear the dataArray and filter from main array.
The class will be like below.
class SearchViewController: UIViewController,
UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var myArray:NSMutableArray = NSMutableArray()
var myFilteredArray:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
//fetch the data save in myArray
}
override func viewWillAppear(_ animated: Bool) {
searchBar.becomeFirstResponder()
}
// MARK: - SearchBar delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.FilterResults(searchText: searchBar.text!)
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
}
func FilterResults(searchText:String) {
myFilteredArray = NSMutableArray()
let myPredicate = NSPredicate(format: "title contains[c]", searchText)
myFilteredArray = NSMutableArray(array: myArray.filtered(using: myPredicate))
self.TableView.reloadData()
}
}
Comments
Post a Comment