Rohit
Rohit

Reputation: 2326

Change tableview data according to textfield in swift

I want to change the TableView data according to Textfield. when a user taps on Textfield and starts editing it will change the TableView data accordingly. I saw a lot of examples on but mainly I found about search bar any help would be appreciated. Please note that this is textfield not seacrhbar

Upvotes: 2

Views: 5095

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

var searchActive : Bool = false

var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]

var filtered:[String] = []


   textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

and handle method:

@objc func textFieldDidChange(_ textField: UITextField) {

 // filter tableViewData with textField.text

  let searchText  = textField.text

  filtered = data.filter({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
     self.tableView.reloadData()

}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


  let cell = tableView.dequeueReusableCell(withIdentifier:CellIdentifier1) as! generalTableViewCell

    if(searchActive){
        cell.titlelb.text = filtered[indexPath.row]
    } else {
        cell.titlelb.text = data[indexPath.row];
    }
 }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(searchActive){
       return filtered.count
    } else {
        return data.count
    }
}

Upvotes: 8

hardik parmar
hardik parmar

Reputation: 853

You can implement textFieldDelegate in the view controller and then in the delegate method textFieldDidChange you can change the tableview datasource according to your use and reload the tableview after that.

Upvotes: 1

Related Questions