Here is my single line Search functionality code which is not filtering results properly. Can anyone let me know what I have to change in the code to display the array elements I am searching with first three characters of text.
For the first character I entered it is showing results. But entering second and third elements it is not showing any results
Search Functionality Logic:
searchFruit = data.filter{$0.range(of: textSearched, options: [.caseInsensitive, .anchored]) != nil}
try this:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var data = ["apple","bananna","dragon fruit", "mango","pineapple"]
var searchFruit = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
searchFruit = data
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchFruit.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = searchFruit[indexPath.row]
return cell!
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchFruit = (searchText.isEmpty) ? self.data : self.data.filter({ (searchValue) -> Bool in
return searchValue.range(of: searchText, options: .caseInsensitive) != nil
})
tableView.reloadData()
}
}