naga
naga

Reputation: 397

search bar controller in swift

I am new to swift programming

search bar controller in tableview header. I can give the search name manually its working fine but in my case I have to give the name in the search bar controller and display the name of the student. search bar controller take the searched text use the filter option.

this is code

 let searchController = UISearchController(searchResultsController: nil)

      override func viewDidLoad() {
            searchController.searchResultsUpdater = self
            searchController.hidesNavigationBarDuringPresentation = false
            searchController.dimsBackgroundDuringPresentation = false
            tableView.tableHeaderView = searchController.searchBar
            searchController.delegate = self
            self.searchController.searchBar.delegate = self
    }

    func updateSearchResults(for searchController: UISearchController) {

        _ = kidsData
        let searchToSearch = "Savitha"

        if(searchToSearch == ""){
           self.kidsData = self.KidsDataDuplicate
        } else{
            self.kidsData.removeAll()

            let itemsarray = self.KidsDataDuplicate

            var forkidsinArray = [String]()

        for Kids in itemsarray {
            forkidsinArray.append(Kids.name)
            if(Kids.name.range(of: searchToSearch, options: .caseInsensitive) != nil){
                self.kidsData.append(Kids)
            }
        }
            self.tableView.reloadData()
        }
    }

take the text to search controller using filter

enter image description here

pls help me

Upvotes: 1

Views: 3426

Answers (2)

devang bhatt
devang bhatt

Reputation: 470

You can use shouldChangeTextIn Delegate method of UISearchBar.

  func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    let newCharLength = (searchBar.text ?? "").characters.count + text.characters.count - range.length

    if newCharLength.count > 0 {

        arrSearchFilter = arrNames.filter { (str) -> Bool in
                    return (str.lowercased().contains((searchBar.text?.lowercased())!))!
                }

             if arrSearchLocalityModel.count > 0 {
                    arrSearchLocality = arrSearchLocalityModel
                } else {
                    arrSearchLocality = arrLocalityModel
                }

          self.tableView.reloadData()

        }


    }

Upvotes: 0

Aravind A R
Aravind A R

Reputation: 2714

From the question I believe you are performing the search correctly but you want to get the word/text which is entered in the searchBar to perform the search. We will get the text entered in searchBar using the searchBar.text property of UISearchBarController

Try

let searchToSearch = searchController.searchBar.text

Upvotes: 1

Related Questions