JessJ JessJ - 2 months ago 4x
iOS Question

How can I reload all of data in tableview when I click cancel on search bar?(IOS/Swift)

I added

and when I click the cancel button, I want to reload all the data on the tableview. But it shows the cell filtered by search bar. Instead of showing only search result, How can I reload all the data again?

@IBOutlet weak var mySearchBar: UISearchBar!
@IBOutlet var myTableView: UITableView!

var foods = [Food]()
var foodsSearching = [Food]()

// search in progress or not
var isSearching : Bool = false

override func viewDidLoad() {

// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem()

if let savedFoods = loadFoods() {
foods += savedFoods
} else {


// set table view delegate
self.myTableView.dataSource = self
self.myTableView.delegate = self

// set search bar delegate
self.mySearchBar.delegate = self


// hide keyboard when cancel button clicked
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.mySearchBar.text = ""

self.myTableView.dataSource = self
self.myTableView.delegate = self

//need to reload all of data..not only the cells filtered by search bar



Set isSearching to false on searchBarCancelButtonClicked before reloading the table view. On tableview delegates, check if isSearching is true then use foods array, otherwise use foodsSearching array.