I am extremely new to Xcode and swift and currently working on a school project. I have linked the UISearchBar to the UITableView and am able to search properly. However, the issue I am having is when I use the search bar to click on an item the image linked to the item won't pop up on the next page. It works well when I don't search the item and click right from table view. Here's my code.
#IBOutlet weak var schoolSearch: UISearchBar!
#IBOutlet weak var tblView: UITableView!
let schoolnames = ["Long Beach City College LAC", "California State University, Bakersfield", "California State University, Cal Maritime", "California State University, Channel Islands", "California State University, Chico", "California State University, Dominguez Hills", "California State University, East Bay", "California State University, Fresno", "California State University, Fullerton", "California State University, Humboldt", "California State University, Long Beach", "California State University, Los Angeles", "California State University, Monterey Bay", "California State University, Northridge", "California State Polytechnic University, Pomona", "California State University, Sacramento", "California State University, San Bernardino", "California State University, San Diego", "California State University, San Francisco", "California State University, San Jose", "California Polytechnic State University, San Luis Obispo", "California State University, San Marcos", "California State University, Sonoma", "California State University, Stanislaus", "University of California Berkeley", "University of California Davis", "University of California Irvine", "University of California Los Angeles", "University of California Merced", "University of California Riverside", "University of California San Diego", "University of California San Francisco", "University of California Santa Barbara", "University of California Santa Cruz", "Long Beach City College PCC", "El Camino College Torrance", "El Camino College Compton", "Cerritos College", "Cypress College"]
var searchedSchool = [String]()
var searching = false
override func viewDidLoad() {
super.viewDidLoad()
schoolSearch.delegate = self
self.tblView.delegate = self
self.tblView.reloadData()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension ChooseSchool: UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchedSchool.count
} else {
return schoolnames.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell
cell?.img.image = UIImage(named: schoolnames[indexPath.row])
cell?.lbl.text = schoolnames[indexPath.row]
_ = tableView.dequeueReusableCell(withIdentifier: "cell")
if searching {
cell?.textLabel?.text = searchedSchool[indexPath.row]
} else{
cell?.textLabel?.text = schoolnames[indexPath.row]
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "TestController") as? TestController
vc?.schoolnames = schoolnames[indexPath.row]
navigationController?.pushViewController(vc!, animated: true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchedSchool = schoolnames.filter { $0.range(of: searchText, options: .caseInsensitive) != nil }
searching = true
tblView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tblView.reloadData()
}
}
`
Problem is your data source: schoolnames vs searchedSchool. In you didSelectRowAt you have to set condition.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "TestController") as? TestController
if searching {
vc?.schoolnames = searchedSchool[indexPath.row]
} else {
vc?.schoolnames = schoolnames[indexPath.row]
}
navigationController?.pushViewController(vc!, animated: true)
}
Related
I am trying to follow-up with this tutorial on CodePath: Visit https://guides.codepath.com/ios/Search-Bar-Guide#cancelling-out-of-search-and-hiding-keyboard
I created a SearchViewController to search but then didSelectRowAt doesn't work
This is my code below:
class SearchViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
"Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
"Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
"Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
"Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]
var filteredData: [String]!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.allowsSelection = true
searchBar.delegate = self
filteredData = data
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = filteredData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
// THIS IS NOT WORKING
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("didSelectRowAt(\(indexPath)")
}
// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// When there is no text, filteredData is the same as the original data
// When user has entered text into the search box
// Use the filter method to iterate over all items in the data array
// For each item, return true if the item should be included and false if the
// item should NOT be included
filteredData = searchText.isEmpty ? data : data!.filter { (item: String) -> Bool in
// If dataItem matches the searchText, return true to include it
return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
}
}
Is there something else I need to do? The tutorial doesn't show any other code I was missing.
You should the UITableViewDelegate delegate to your class and tableView.delegate = self in your viewDidLoad function. This will help to trigger the delegates functions of the UITableViewController.
In Your viewDidLoad() method
tableView.delegate = self
tableView.dataSource = self
import UIKit
let country = ["Argentina", "Australia", "Belgium", "Brazil", "Colombia", "Costa Rica", "Croatia", "Denmark", "Egypt", "England", "France", "Germany", "Iceland", "Iran", "Japan", "Mexico", "Morocco", "Nigeria", "Panama", "Peru", "Poland", "Portugal", "Republic of Korea", "Russia", "Saudi Arabia", "Senegal", "Serbia", "Spain", "Sweden", "Switzerland", "Tunis", "Uruguay"]
let country2 = ["Argentina2", "Australia2", "Belgium2", "Brazil2", "Colombia2", "Costa Rica2", "Croatia2", "Denmark2", "Egypt2", "England2", "France2", "Germany2", "Iceland2", "Iran2", "Japan2", "Mexico2", "Morocco2", "Nigeria2", "Panama2", "Peru2", "Poland2", "Portugal2", "Republic of Korea2", "Russia2", "Saudi Arabia2", "Senegal2", "Serbia2", "Spain2", "Sweden2", "Switzerland2", "Tunis2", "Uruguay2"]
let country3 = ["Argentina3", "Australia3", "Belgium3", "Brazil3", "Colombia3", "Costa Rica3", "Croatia3", "Denmark3", "Egypt3", "England3", "France3", "Germany3", "Iceland3", "Iran3", "Japan3", "Mexico3", "Morocco3", "Nigeria3", "Panama3", "Peru3", "Poland3", "Portugal3", "Republic of Korea3", "Russia3", "Saudi Arabia3", "Senegal3", "Serbia3", "Spain3", "Sweden3", "Switzerland3", "Tunis3", "Uruguay3"]
var myIndex = 0
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredArray = country.filter({$0.lowercased().contains(searchText.lowercased())})
if searchText == "" {
filteredArray = country
}
self.tableView.reloadData()
}
var filteredArray = [String]()
var searchController = UISearchController()
var searchBar = UISearchBar()
var resultController = UITableViewController()
let country = ["Argentina", "Australia", "Belgium", "Brazil", "Colombia", "Costa Rica", "Croatia", "Denmark", "Egypt", "England", "France", "Germany", "Iceland", "Iran", "Japan", "Mexico", "Morocco", "Nigeria", "Panama", "Peru", "Poland", "Portugal", "Republic of Korea", "Russia", "Saudi Arabia", "Senegal", "Serbia", "Spain", "Sweden", "Switzerland", "Tunis", "Uruguay"]
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
filteredArray = country
searchBar.frame = CGRect(x: 0, y: 0, width: 400, height: 50)
self.tableView.tableHeaderView = searchBar
self.searchBar.delegate = self
definesPresentationContext = true
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.font = UIFont.systemFont(ofSize: 18.0)
cell.textLabel?.text = self.filteredArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "seque", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "seque" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let viewController: ViewController = segue.destination as! ViewController
viewController.myIndex = indexPath
}
}
}
}
There are some problem in your code:
In cellForRow you are dequeuing your Table View, Not the tableView given by delegate method. self.tableView.dequeueReusableCell(withIdentifier: Here do not use self.
You are using resultController which does not have any prototype cell to display data. Here your app will crash.
I do not understand what you have done in prepareForSegue
Do not use any global variable. If you want to use myIndex, make a property in destinationVC and pass it prepareForSegue.
You are displaying filteredArray on table view and on selection getting value from country array, that's why you are getting wrong value.
What I found is, you do not need a SearchViewController because you are using a single View controller to display your filtered data.
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredArray = country.filter({$0.lowercased().contains(searchText.lowercased())})
if searchText == "" {
filteredArray = country
}
self.tableView.reloadData()
}
var filteredArray = [String]()
var searchController = UISearchController()
var searchBar = UISearchBar()
var resultController = UITableViewController()
let country = ["Argentina", "Australia", "Belgium", "Brazil", "Colombia", "Costa Rica", "Croatia", "Denmark", "Egypt", "England", "France", "Germany", "Iceland", "Iran", "Japan", "Mexico", "Morocco", "Nigeria", "Panama", "Peru", "Poland", "Portugal", "Republic of Korea", "Russia", "Saudi Arabia", "Senegal", "Serbia", "Spain", "Sweden", "Switzerland", "Tunis", "Uruguay"]
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
filteredArray = country
searchBar.frame = CGRect(x: 0, y: 0, width: 400, height: 50)
self.tableView.tableHeaderView = searchBar
self.searchBar.delegate = self
definesPresentationContext = true
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.font = UIFont.systemFont(ofSize: 18.0)
cell.textLabel?.text = self.filteredArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "seque", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "seque" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let viewController: ViewController = segue.destination as! ViewController
let newIndex: Int = country.index(of: filteredArray[indexPath.row])!
viewController.myIndex = newIndex
}
}
}
}
Please let me know if this worked.
EDIT
Your class ViewController should look like:
class ViewController: UIViewController {
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var myImageView2: UIImageView!
#IBOutlet weak var myImageView3: UIImageView!
var myIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
myImageView.image = UIImage(named: country[myIndex])
myImageView2.image = UIImage(named:country2[myIndex])
myImageView3.image = UIImage(named: country3[myIndex])
}
// Other methods
}
I am in the process of making my first app. Right now I am trying to make a settings page. So far it looks like this.
I have the split view controller hooked up to a master view controller and a detail view controller (code below). As you can see, right now there is a table view on the left side of the split view controller containing different buttons. When each button is pressed I want it to display a list of words on the right side of the view controller. It does display a list of words already but I want it to display the words stacked horizontally in a table view and I am not sure how to go about doing this.
//
// MasterViewController.swift
// firstapp
//
// Created by Anthony Rubin on 7/18/17.
// Copyright © 2017 rubin. All rights reserved.
//
import UIKit
protocol WordSelectionDelegate: class {
func wordSelected(newWord: Word)
}
class MasterViewController: UITableViewController {
var words = [Word]()
weak var delegate: WordSelectionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.words.append(Word(name: "initial /l/ 1 syllable", description: "lake lamb lamp lark leaf leash left leg lime lion lips list lock log look love lunch"))
self.words.append(Word(name: "initial /l/ multisyllabic", description: "words, words, words, words"))
self.words.append(Word(name: "intersyllabic /l/", description: "words, words, words, words"))
self.words.append(Word(name: "final /l/", description: "words, words, words, words"))
self.words.append(Word(name: "initial /pl/", description: "words, words, words, words"))
self.words.append(Word(name: "initial /bl/", description: "words, words, words, words"))
self.words.append(Word(name: "initial /fl/", description: ""))
self.words.append(Word(name: "initial /gl/", description: "words, words, words, words"))
self.words.append(Word(name: "initial /kl/", description: ""))
self.words.append(Word(name: "initial /sl/", description: ""))
self.words.append(Word(name: "final /l/ clusters", description: ""))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.words.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
let word = self.words[indexPath.row]
cell.textLabel?.text = word.name
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath) {
let selectedMonster = self.words[indexPath.row]
self.delegate?.wordSelected(newWord: selectedMonster)
if let Detail = self.delegate as? Detail {
splitViewController?.showDetailViewController(Detail, sender: nil)
}
}
__
import UIKit
class Detail: UIViewController {
#IBOutlet weak var descriptionLabel: UILabel!
var word: Word! {
didSet (newWord) {
self.refreshUI()
}
}
func refreshUI() {
descriptionLabel?.text = word.description
}
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension Detail: WordSelectionDelegate {
func wordSelected(newWord: Word) {
word = newWord
}
}
--
class Word {
let name: String
let description: String
init(name: String, description: String) {
self.name = name
self.description = description
}
}
--
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let splitViewController = self.window!.rootViewController as! UISplitViewController
let leftNavController = splitViewController.viewControllers.first as! UINavigationController
let MasterViewController = leftNavController.topViewController as! MasterViewController
let Detail = splitViewController.viewControllers.last as! Detail
let firstWord = MasterViewController.words.first
Detail.word = firstWord
MasterViewController.delegate = Detail
return true
}
PS. If you look at the MasterViewController code you will see where it says "description". the lists contained in description is what should be displayed in the table view on the right.
In the func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath), of the masterviewcontroller, you need to replace the viewcontroller.
Get the splitviewcontroller instance from the appdelegate, now to the splitview controllers view controller property assign your desired viewcontroller object, and make sure your desired view controller object has a navigation controller.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let splitViewController = appDelegate.window!.rootViewController as! UISplitViewController
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "yourviewcontrollername") as! UINavigationController
splitViewController.viewControllers[1] = nextViewController
}
I'll preface this saying I'm new to Swift. I have a label that displays a user entered variable that has been passed from the previous view controller. Below that table is a tableview. Currently the tableview is displaying an array of cities that I've hardcoded into the view. I'd like that tableview to be filtered based on the variable that is displayed in the label. i.e. if the label shows "Las Vegas", I want the tableview to only display rows that contain "Las Vegas". Filtering is what I'm having a problem figuring out. Here's what I have so far.
import UIKit
class ResultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cities = [
("Orlando", "FL, United States", "Location"),
("Orlando", "AR, United States", "Location"),
("Orlando", "KY, United States", "Location"),
("Orlando", "NC, United States", "Location"),
("Orlando", "OK, United States", "Location"),
("Orlando", "NY, United States", "Location"),
("Orlando", "VA, United States", "Location"),
("Orlando", "WV, United States", "Location"),
("Las Vegas", "NV, United States", "Location"),
("Las Vegas", "TX, United States", "Location"),
("Las Vegas", "NM, United States", "Location"),
("Scottsdale", "AZ, United States", "Location"),
("Scottsdale Plaza", "PA, United States", "Location"),
("Scottsdale Pond", "CA, United States", "Location"),
("Scottsdale Park", "IL, United States", "Location")]
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(cities.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ResultsControllerTableViewCell
let (labelCity, labelState, labelType) = cities[indexPath.row]
cell.cityName.text = labelCity
cell.stateName.text = labelState
cell.resultType.text = labelType
return(cell)
}
#IBOutlet weak var userSearchInputLabel: UILabel!
var searchItem = String()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
userSearchInputLabel.text = searchItem
self.extendedLayoutIncludesOpaqueBars=true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
self.navigationItem.hidesBackButton = true
}
Pretty basic skeleton code:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.filter { $0.contains(self.filterText) }.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ResultsControllerTableViewCell
let (labelCity, labelState, labelType) = cities.filter { $0.contains(self.filterText) }[indexPath.row]
cell.cityName.text = labelCity
cell.stateName.text = labelState
cell.resultType.text = labelType
return(cell)
}
public func textViewDidChange(sender: UITextView, newText: String) {
self.filterText = newText
self.tableView.reloadData()
}
I coded this without an IDE, there may be a few syntax errors, but basically alter your tableview to filter based on some filterText that's updated whenever the textview is updated.
I add a search bar by adding subview into a UIView. When I tap the search bar, cancel button shows up, however the keyboard disappear immediately. I have to tap the search bar again so that I can input some text for searching.
Any thoughts?
Use the following code:
import UIKit
class ViewController: UIViewController,UISearchDisplayDelegate, UISearchBarDelegate,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var headingLabel: UILabel!
#IBOutlet weak var countriesTableView: UITableView!
#IBOutlet weak var countrySerachBar: UISearchBar!
var marrCountryList = [String]()
var marrFilteredCountryList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.countriesTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
marrCountryList = ["USA", "Bahamas", "Brazil", "Canada", "Republic of China", "Cuba", "Egypt", "Fiji", "France", "Germany", "Iceland", "India", "Indonesia", "Jamaica", "Kenya", "Madagascar", "Mexico", "Nepal", "Oman", "Pakistan", "Poland", "Singapore", "Somalia", "Switzerland", "Turkey", "UAE", "Vatican City"]
self.countriesTableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.countrySerachBar.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.marrFilteredCountryList.count
} else {
return self.marrCountryList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cellCountry = self.countriesTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var countryName : String!
if tableView == self.searchDisplayController!.searchResultsTableView {
countryName = marrFilteredCountryList[(indexPath as NSIndexPath).row]
} else {
countryName = marrCountryList[(indexPath as NSIndexPath).row]
}
cellCountry.textLabel?.text = countryName
return cellCountry
}
func filterTableViewForEnterText(_ searchText: String) {
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchText)
let array = (self.marrCountryList as NSArray).filtered(using: searchPredicate)
self.marrFilteredCountryList = array as! [String]
self.countriesTableView.reloadData()
}
func searchDisplayController(_ controller: UISearchDisplayController, shouldReloadTableForSearch searchString: String?) -> Bool {
self.filterTableViewForEnterText(searchString!)
return true
}
func searchDisplayController(_ controller: UISearchDisplayController,
shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterTableViewForEnterText(self.searchDisplayController!.searchBar.text!)
return true
}
}
Storyboard screenshot:
Output:
Please check my GitHub link to test sample project:
https://github.com/k-sathireddy/SearchDisplayControllerSample