Search code examples
swifttableviewsearchbar

Delete text on searchbar and return to view before the search. SWIFT


I already have some items that are shown on tableview. When I do a search using searchbar, the same tableview is updated with new items.(My project today).

But If I erase what I wrote on searchbar, I need to return for the items they were before. How can I do that ?

     import UIKit
     import Alamofire

 class MovieViewController: UIViewController, AsyncUpdateProtocol,UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {


@IBOutlet weak var myTable: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var myArray: Array<Movie>!
var movieData: MovieData!


override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    self.myTable.dataSource = self
    self.movieData = MovieData(controllerUpdate: self)
    self.myArray = self.movieData.data
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.movieData.data.count;
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: AnyObject = self.myTable.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
    cell.textLabel!!.text = self.movieData.data[indexPath.row].title
    cell.textLabel!!.adjustsFontSizeToFitWidth = true
    var url: NSURL
    if((self.movieData.data[indexPath.row].poster ) != nil){
        url = NSURL(string: "http://image.tmdb.org/t/p/w500\(self.movieData.data[indexPath.row].poster)") as NSURL!
    }else{
        url = NSURL(string: "http://developer-agent.com/wp-content/uploads/2015/05/images_no_image_jpg3.jpg") as NSURL!
    }
    var data = NSData(contentsOfURL: url) as NSData!
    var imagem = UIImage(data: data!)
    cell.imageView!!.image = imagem
    return cell as! UITableViewCell
}
 func searchBarSearchButtonClicked(searchBar: UISearchBar){
    pesquisa(searchBar.text)
    searchBar.resignFirstResponder()
}


 func pesquisa(nome: String){
    self.movieData.data.removeAll()
    self.movieData.request(nome)
}

Solution

  • You should use the UISearchBar delegate method for textDidChange and check for nil, if it's nil then you can load your data like in your view did load, here's what I mean:

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    
        if searchText.isEmpty == true {
    
            self.movieData = MovieData(controllerUpdate: self)
    
        } 
    
    }