Search Controller no results (blank page) - ios

The basic table shows the results correctly - it work properly.
I have a problem with a table that shows the search results, always returns a white page. (no results) The problem may be two tables in one controller?
What am I doing wrong?
class SearchMagazineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
#IBOutlet var tableView: UITableView!
var resultsController: UITableViewController!
var searchController: UISearchController!
var searchMagazines: [Magazine]?
var latestPub = [Magazine]()
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text!
if searchText.count > 0 {
self.searchMagazines = CoreDataHandler.searchMagazine(query: searchText, scope: 0)
}
self.resultsController.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
latestPub = CoreDataHandler.latestMagazines() ?? [Magazine]()
resultsController = UITableViewController(style: .plain)
resultsController.tableView.register(UINib(nibName: "searchCell", bundle: nil), forCellReuseIdentifier: "searchCell")
resultsController.tableView.dataSource = self
resultsController.tableView.delegate = self
searchController = UISearchController(searchResultsController: resultsController)
searchController.delegate = self
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = true
navigationItem.searchController = searchController
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.resultsController {
return searchMagazines?.count ?? 0
}else{
return latestPub.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.resultsController {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchCell
let item = searchMagazines![indexPath.row]
cell.cat.text = TitleReturn(id: item.cat)
return cell
}else{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell") as? SearchTableViewCell else { return UITableViewCell() }
cell.title.text = latestPub[indexPath.row].title
return cell
}
}
}

Related

UISearchBar to filter custom UITableViewCells

I am trying to filter custom UITableViewCells, based on one of the UILabels present in the cell.
All of the data is parsed from remote JSON, which has the model locally named Item and currently I am displaying the following in each cell successfully:
var titleLabel = UILabel()
var descriptionLabel = UILabel()
Also defined in my ItemTableViewCell class is:
func set(product: Item) {
DispatchQueue.main.async { [weak self] in
self?.titleLabel.text = item.title
self?.descriptionLabel.text = item.listPrice
}
}
These are called within my main View Controller, to which I have added a searchBar successfully and is visible within the app:
import Foundation
import UIKit
class ItemsListViewController: UIViewController {
var items = [Items]()
var itemsSearch: [Items] = []
var tableView = UITableView()
var searchController = UISearchController()
struct Cells {
static let itemCell = "ItemCell"
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
configureSearchController()
}
func configureSearchController() {
searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.placeholder = "Search items"
definesPresentationContext = true
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
}
func configureTableView() {
view.addSubview(tableView)
setTableViewDelegates()
tableView.rowHeight = 100
tableView.pin(to: view)
tableView.register(itemTableViewCell.self, forCellReuseIdentifier: Cells.itemCell)
}
func setTableViewDelegates() {
tableView.delegate = self
tableView.dataSource = self
}
}
extension itemsListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.itemCell) as! itemTableViewCell
let item = items[indexPath.row]
cell.set(item: item)
return cell
}
}
extension ItemsListViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
}
}
How can I filter these cells so say for instance a user searches for "Food", the only items which return would be ones which have a cell titleLabel = "food"?
I've tried to implement a function similar to the below, however it fails to achieve what I am after:
func filterContentForSearchText(_ searchText: String, category: = nil) {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.productCell) as! ProductTableViewCell
productsSearch = products.filter { (cell: cell) -> Bool in
return products.name.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
Thanks in advance for any help here.
You can not filter TableViewCells. You have to filter your model data and instead of using UISearchResultsUpdating you should use UISearchBarDelegate
I have modified your code, check it.
class ItemsListViewController: UIViewController {
var items = [Items]()
var itemsSearch: [Items] = []
var filterActive = false
var tableView = UITableView()
var searchController = UISearchController()
struct Cells {
static let itemCell = "ItemCell"
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
configureSearchController()
}
func configureSearchController() {
searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.placeholder = "Search items"
searchController.searchBar.delegate = self
definesPresentationContext = true
}
func configureTableView() {
view.addSubview(tableView)
setTableViewDelegates()
tableView.rowHeight = 100
tableView.pin(to: view)
tableView.register(itemTableViewCell.self, forCellReuseIdentifier: Cells.itemCell)
}
func setTableViewDelegates() {
tableView.delegate = self
tableView.dataSource = self
}
}
extension ItemsListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterActive ? itemsSearch.count : items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.itemCell) as! itemTableViewCell
let item = filterActive ? itemsSearch[indexPath.row] : items[indexPath.row]
cell.set(item: item)
return cell
}
}
extension ItemsListViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filterItems(text: searchController.searchBar.text)
}
func filterItems(text: String?) {
guard let text = text else {
filterActive = false
self.tableView.reloadData()
return
}
self.itemsSearch = self.items.filter({ (item) -> Bool in
return item.title.lowercased().contains(text.lowercased())
})
filterActive = true
self.tableView.reloadData()
}
// Edited Version
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
filterActive = false
self.tableView.reloadData()
}
}
You are doing it the wrong way.
You should not filter the cells, but instead filter the model (e.g. add and remove entries to the table view data source)
Then call reloadData - this will then access the filtered model (in cellForRowAt and create only the filtered amount of (visible) cells
To improve, use a diffable data source

I can not solve the error "coding classification not key value coding-compliant for the key"

It is a question.
This class is not key value code-compliant for the key error is given.
However, I am not sure which part is wrong. This error appears at cellForRowAt.
Thank you for your answer.
If you want it, I can also show the code of ContentTableViewCell, so please call out.
import UIKit
class SearchViewController: UIViewController, UISearchResultsUpdating {
#IBOutlet weak var tableview: UITableView!
var songs = [
"裁量権を持って、若者向けカレンダーアプリ開発をしたいiOSエンジニア募集!",
"自信を持って、応援出来るエンジニアを募集!"
]
var searchSongs = [String]()
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text!
searchSongs = songs.filter {(name) -> Bool in
return name.contains(searchString)
}
tableview.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
let searchController = UISearchController(searchResultsController:nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
navigationItem.searchController = searchController
definesPresentationContext = true
delegate()
}
}
extension searchViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if navigationItem.searchController?.isActive == true {
return searchSongs.count
} else {
return songs.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "ContentTableViewCell", for: indexPath) as! ContentTableViewCell
if navigationItem.searchController?.isActive == true {
cell.commonInit(content: searchSongs[indexPath.row])
} else {
cell.commonInit(content: songs[indexPath.row])
}
return cell
}
func delegate() {
tableview.delegate = self
tableview.dataSource = self
let nibName = UINib(nibName: "ContentTableViewCell", bundle: nil)
self.tableview.register(nibName, forCellReuseIdentifier: "ContentTableViewCell")
}
}
Check in your Storyboard. I think any outlet is not connected properly.
Check is there any yellow warning triangle in your storyboard on which screen this error is coming. If you found any, remove and connect the outlet again.

Swift - Having problems with SearchBar in a custom TableViewController

I am new to code and I want to make an Search function in my Custom TableViewController. I get an error (Thread 1: signal SIGABRT) when I type (in the search bar) in a letter which correspond to a letter in an list of names (var namen*) I made. When I type in a letter which not correspond to a letter in my list of names I don't get the error. I checked my IBoutlets but they were not the problem. Does someone know how to fix the error?
Here's my initial viewcontroller code: (some names are Dutch)
import UIKit
class elementstableviewcontroller: UITableViewController,
UISearchResultsUpdating{
#IBOutlet var tableview: UITableView!
var namen = ["Waterstof","Helium","Litium","Beryllium","Boor","Koolstof","Stikstof","Zuurstof","Fluor","Neon"]
var afkortingen = ["H","He","Li","Be","B","C","N","O","F","Ne"]
var atoommassas = ["Massa: 1,008","Massa: 4,003","Massa: 6,941","Massa: 9,012","Massa: 10,81","Massa: 12,01","Massa: 14,01","Massa: 16,00","Massa: 19,00","Massa: 20,18"]
var atoomnummers = ["Nummer: 1","Nummer: 2","Nummer: 3","Nummer: 4","Nummer: 5","Nummer: 6","Nummer: 7","Nummer: 8","Nummer: 9","Nummer: 10"]
var ladingen = ["Lading: +1,-1","Lading: 0","Lading: +1","Lading: +2","Lading: +3","Lading: +2,+4,-4","Lading: +1,+2,+3,+4,+5,-1,-2,-3","Lading: -2","Lading: -1","Lading: 0"]
var electronenconfig = ["Config: 1","Config: 2","Config: 2,1","Config: 2,2","Config: 2,3","Config: 2,4","Config: 2,5","Config: 2,6","Config: 2,7","Config: 2,8"]
var searchcontroller : UISearchController!
var resultscontroller = UITableViewController()
var filterednamen = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.resultscontroller.tableView.dataSource = self
self.resultscontroller.tableView.delegate = self
self.searchcontroller = UISearchController(searchResultsController: self.resultscontroller)
self.tableView.tableHeaderView = self.searchcontroller.searchBar
self.searchcontroller.searchResultsUpdater = self
self.searchcontroller.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
}
func updateSearchResults(for searchController: UISearchController) {
self.filterednamen = self.namen.filter { (naam:String) -> Bool in
if naam.lowercased().contains(self.searchcontroller.searchBar.text!.lowercased()) {
return true
}else{
return false
}
}
self.resultscontroller.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView{
return self.namen.count
}else {
return self.filterednamen.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.afkorting.text = afkortingen[indexPath.row]
cell.name.text = namen[indexPath.row]
cell.atoommassa.text = atoommassas[indexPath.row]
cell.elektronenconfiguratie.text = electronenconfig[indexPath.row]
cell.atoomnummer.text = atoomnummers[indexPath.row]
cell.lading.text = ladingen[indexPath.row]
if tableView == self.tableView{
//cell.textLabel?.text = self.namen[indexPath.row]
cell.name.text = self.namen[indexPath.row]
}else{
//cell.textLabel?.text = self.filterednamen[indexPath.row]
cell.name.text = self.filterednamen[indexPath.row]
}
return cell
}
}
And here's my CustomCell code:
import UIKit
class CustomCell: UITableViewCell {
#IBOutlet var elektronenconfiguratie: UILabel!
#IBOutlet var atoomnummer: UILabel!
#IBOutlet var atoommassa: UILabel!
#IBOutlet var name: UILabel!
#IBOutlet var afkorting: UILabel!
#IBOutlet var lading: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
*namen = names and naam = name translated from Dutch to English
Try to implement filter functionality in shouldChangeTextIn SearchBar method as given below
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
self.filterednamen = self.namen.filter { (naam:String) -> Bool in
return naam.lowercased().contains(self.searchcontroller.searchBar.text!.lowercased())
}
self.resultscontroller.tableView.reloadData()
}
There are several problems with your code.
Firstly, you are creating an IBOutlet of a UITableView unnecessarily. Remove that from your code.
Secondly, you are using that table view for checking if you are searching or not. That is unneccesary, as you want to show search results in the same view controller, so the correct boolean check for that instead is:
!searchcontroller.isActive || searchcontroller.searchBar.text == ""
Lastly, the error occurs exactly because the last issue stated: you are setting the searchResultsController to a phantom table view, so it gets an assertion failure, as it can't find a cell identified "cell".
Here is the fixed code:
import UIKit
class FirstViewController: UITableViewController,
UISearchResultsUpdating{
var namen = ["Waterstof","Helium","Litium","Beryllium","Boor","Koolstof","Stikstof","Zuurstof","Fluor","Neon"]
var afkortingen = ["H","He","Li","Be","B","C","N","O","F","Ne"]
var atoommassas = ["Massa: 1,008","Massa: 4,003","Massa: 6,941","Massa: 9,012","Massa: 10,81","Massa: 12,01","Massa: 14,01","Massa: 16,00","Massa: 19,00","Massa: 20,18"]
var atoomnummers = ["Nummer: 1","Nummer: 2","Nummer: 3","Nummer: 4","Nummer: 5","Nummer: 6","Nummer: 7","Nummer: 8","Nummer: 9","Nummer: 10"]
var ladingen = ["Lading: +1,-1","Lading: 0","Lading: +1","Lading: +2","Lading: +3","Lading: +2,+4,-4","Lading: +1,+2,+3,+4,+5,-1,-2,-3","Lading: -2","Lading: -1","Lading: 0"]
var electronenconfig = ["Config: 1","Config: 2","Config: 2,1","Config: 2,2","Config: 2,3","Config: 2,4","Config: 2,5","Config: 2,6","Config: 2,7","Config: 2,8"]
var searchcontroller : UISearchController!
var filterednamen = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.searchcontroller = UISearchController(searchResultsController: nil)
self.tableView.tableHeaderView = self.searchcontroller.searchBar
self.searchcontroller.searchResultsUpdater = self
self.searchcontroller.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
}
func updateSearchResults(for searchController: UISearchController) {
self.filterednamen = self.namen.filter { (naam:String) -> Bool in
if naam.lowercased().contains(self.searchcontroller.searchBar.text!.lowercased()) {
return true
}else{
return false
}
}
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !searchcontroller.isActive || searchcontroller.searchBar.text == "" {
return self.namen.count
}else {
return self.filterednamen.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.afkorting.text = afkortingen[indexPath.row]
cell.name.text = namen[indexPath.row]
cell.atoommassa.text = atoommassas[indexPath.row]
cell.elektronenconfiguratie.text = electronenconfig[indexPath.row]
cell.atoomnummer.text = atoomnummers[indexPath.row]
cell.lading.text = ladingen[indexPath.row]
if !searchcontroller.isActive || searchcontroller.searchBar.text == "" {
//cell.textLabel?.text = self.namen[indexPath.row]
cell.name.text = self.namen[indexPath.row]
}else{
//cell.textLabel?.text = self.filterednamen[indexPath.row]
cell.name.text = self.filterednamen[indexPath.row]
}
return cell
}
}

Add a search bar to custom Table View

I am creating a custom tableViewController with searchBar. I created a custom cell class "DataCell".
With following code searchBar is not shown and array of label is not displayed.
How can I solve this problem?
import UIKit
class DataCell: UITableViewCell{
#IBOutlet weak var label: UILabel!
}
class SearchController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
var isSearching = false
var data = ["a","b","c","d","e"]
var filterData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching{
return filterData.count
}
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as? DataCell {
let text: String!
if isSearching {
text = filterData[indexPath.row]
} else {
text = data[indexPath.row]
}
return cell
} else {
return UITableViewCell()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""{
isSearching = false
view.endEditing(true)
tableView.reloadData()
}else {
isSearching = true
filterData = data.filter({$0 == searchBar.text})
tableView.reloadData()
}
}
}
As of iOS 8, you should be using the [UISearchController][1] for which you need to create 2 classes. A SearchController and a ResultsController. We start by creating a common UITableView class:
import UIKit
class DataCell: UITableViewCell {
#IBOutlet weak var label: UILabel!
func configureCell(_ text: String) {
label.text = text
}
}
Then, for the search class:
class SearchController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var searchController: UISearchController!
var resultController: ResultController?
var data = ["a","b","c","d","e"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TableCell.self, forCellReuseIdentifier: "DataCell")
tableView.register(UINib(nibName: "DataCell", bundle: Bundle.main), forCellReuseIdentifier: "DataCell")
// Search Results
resultController = ResultController()
setupSearchControllerWith(resultController!)
if #available(iOS 9.0, *) {
searchController?.loadViewIfNeeded()
}
tableView.delegate = self
tableView.dataSource = self
resultController.tableView.delegate = self
}
}
extension: SearchController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as? DataCell {
return cell.configureCell(data[indexPath.row])
} else {
return UITableViewCell()
}
}
}
extension SearchController: UITableViewDelegate {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == resultController?.tableView {
performSegue(withIdentifier: "DetailView", sender: resultController?.filterData[indexPath.row])
} else {
performSegue(withIdentifier: "DetailView", sender: data[indexPath.row])
}
}
}
extension SearchController: UISearchResultsUpdating,
UISearchControllerDelegate,
UISearchBarDelegate {
func updateSearchResults(for searchController: UISearchController) {
let resultsTable = searchController.searchResultsController as! ResultVC
// resultsTable.query = searchController.searchBar.text!
resultsTable.filterData = data.filter({
$0 == searchController.searchBar.text!
})
resultsTable.tableView.reloadData()
}
func setupSearchControllerWith(_ results: ResultVC) {
// Register Cells
results.tableView.register(TableCell.self, forCellReuseIdentifier: "DataCell")
results.tableView.register(UINib(nibName: "DataCell", bundle: Bundle.main), forCellReuseIdentifier: "DataCell")
// We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called for both tables.
results.tableView.delegate = self
searchController = UISearchController(searchResultsController: results)
// Set Search Bar
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
tableView.tableHeaderView = searchController.searchBar
// Set delegates
searchController.delegate = self
searchController.searchBar.delegate = self
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""{
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
filterData = data.filter({$0 == searchBar.text})
tableView.reloadData()
}
}
}
Then, for the ResultsController class:
class ResultController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var filterData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TableCell.self, forCellReuseIdentifier: "DataCell")
tableView.register(UINib(nibName: "DataCell", bundle: Bundle.main), forCellReuseIdentifier: "DataCell")
tableView.dataSource = self
}
}
extension ResultController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rowCount = filterData.count
// When no data insert centered label
if rowCount == 0 {
blankView(with: textForEmptyLabel)
} else {
// Remove empty table label
tableView.backgroundView = nil
tableView.separatorStyle = .singleLine
}
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as? DataCell {
return cell.configureCell(filterData[indexPath.row])
} else {
return UITableViewCell()
}
}
}

Search Bar on TableView Does not Work

I'm trying to add a search bar to a simple table view consisting of 7 cells of names and small description for each name.
As in the image here:
I made a class in swift file called Business, that has two attributes: Name and Des.
Here's the code in the view controller:
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var TableView: UITableView!
var B = [Business]() //candies
var filteredNames = [Business]()
let searchController = UISearchController(searchResultsController: nil)
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredNames = B.filter { Bu in
return Bu.Name.lowercaseString.containsString(searchText.lowercaseString)
}
TableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
B = [
Business(Name:"Mariah", Des:"I'm Here to help"),
Business(Name:"Nada", Des:"Hi"),
Business(Name:"Atheer", Des:"Hello"),
Business(Name:"Lojian", Des:"I can Help you"),
Business(Name:"Nadya", Des:"Hayat"),
Business(Name:"Omnia", Des:"Yahoo"),
Business(Name:"Eman", Des:"I have amazing stuff"),
Business(Name:"Amani", Des:"Yess")
]
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
TableView.tableHeaderView = searchController.searchBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredNames.count
}
return B.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.TableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCell
cell.NameLabel.text = B[indexPath.row].Name
cell.DescriptionLabel.text = B[indexPath.row].Des
let Bu: Business
if searchController.active && searchController.searchBar.text != "" {
Bu = filteredNames[indexPath.row]
} else {
Bu = B[indexPath.row]
}
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
}
extension FirstViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController:
(UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
I followed this tutorial to do that:
https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
I don't know whay when I tried to search in simulator the result is always the first cell: Mariah
What's wrong with the code?
You don't use the search result to populate the cells. Replace you cellForRowAtIndexPath with this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.TableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCell
let Bu: Business
if searchController.active && searchController.searchBar.text != "" {
Bu = filteredNames[indexPath.row]
} else {
Bu = B[indexPath.row]
}
cell.NameLabel.text = Bu.Name
cell.DescriptionLabel.text = Bu.Des
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
And, don't use capital first letters for properties.

Resources