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.


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

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift