Raj
Raj

Reputation: 17

TableView displaying same array filtered elements even though array elements not filtered

enter image description here I have 2 buttons and two array list items which shows fruit names and color of the fruit. I implemented search functionality to search fruit and color. The issue here is

  1. Tap on 1st button shows fruit names in a tableview.
  2. Filtered a fruit with name. It retrieves a fruit back
  3. Now tap on outside of the tableview. It dismisses the tableview
  4. Tap on second button fruit color.

Issue arrises. It showing first array elements with search keyword same I entered in the earlier search. Here is my code and screen shots for reference. Where I need to modify the code. Any help is appreciated.

import UIKit

class Cell : UITableViewCell {
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
    
    @IBOutlet weak var selectFruit: UIButton! {
        didSet {
            selectFruit.layer.cornerRadius = 5
        }
    }
    @IBOutlet var selectColor: UIButton! {
        didSet {
            selectColor.layer.cornerRadius = 5
        }
    }
    
    let transparentView = UIView()
    let tableView = UITableView()
    var button = UIButton()
    
    var data = [String]()
    
    var searchData = [String]()
    var searching : Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(Cell.self, forCellReuseIdentifier: "Cell")
        searchData = data
    }
    
    func addTransparentView(frame : CGRect) {
        transparentView.frame = self.view.frame
        self.view.addSubview(transparentView)
        tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0)
        self.view.addSubview(tableView)
        tableView.layer.cornerRadius = 5
        transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.9)
        tableView.reloadData()
        
        let tapgesture = UITapGestureRecognizer(target: self, action: #selector(deleteTransparentView))
        transparentView.addGestureRecognizer(tapgesture)
        transparentView.alpha = 0
        
        UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
            self.transparentView.alpha = 0.5
            self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height + 5, width: frame.width, height: CGFloat(self.data.count * 50))
        }, completion: nil)
    }
    
    @objc func deleteTransparentView() {
        let frame = button.frame
        UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
            self.transparentView.alpha = 0
            self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0)
        }, completion: nil)
    }
    
    @IBAction func selectFruit(_ sender: Any) {
        data = ["Apple","Apricots","Avocados","Oranges","Banana","Grapes","Kiwi","JackFruit","Blueberries","Boysenberries"]
        button = selectFruit
        addTransparentView(frame: selectFruit.frame)
    }
    
    @IBAction func selectColor(_ sender: Any) {
        data = ["Red","Red1","Red2","Red3","Red4","Purple","Purple1","Purple3","Black","LightGreen","Red5"]
        button = selectColor
        addTransparentView(frame: selectColor.frame)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) {
        
        if textSearched.isEmpty {
            searching = false
            searchData.removeAll()
        } else {
            searching = true
            searchData = data.filter{$0.lowercased().contains(textSearched.lowercased())
            }
        }
        tableView.reloadData()
    }
    // MARK:- TableView Methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return searchData.count
        } else {
            return data.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        if searching {
            cell.textLabel?.text = searchData[indexPath.row]
        } else {
            //Todo:  Implement Guard or if  here
            cell.textLabel?.text = data[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let searchBar = UISearchBar(frame: CGRect(x: 10, y: 10, width: tableView.frame.width-20, height: 36))
        searchBar.searchBarStyle = UISearchBar.Style.prominent
        searchBar.placeholder = " Search..."
        searchBar.isTranslucent = false
        searchBar.delegate = self
        return searchBar
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        button.setTitle(data[indexPath.row], for: .normal)
        
        var buttonTitle = ""
        
        if (searchData.count > 0) {
            print("You have searched the fruit \(searchData[indexPath.row])")
            buttonTitle = searchData[indexPath.row]
        } else {
            print("You did not search anyFruit, You just selected \(data[indexPath.row])")
            buttonTitle = data[indexPath.row]
        }
        
        button.setTitle(buttonTitle, for: .normal)
        deleteTransparentView()
    }
}

Upvotes: 1

Views: 52

Answers (1)

Santosh Kumar J M
Santosh Kumar J M

Reputation: 181

try this one

lazy var searchBar:UISearchBar = UISearchBar()

in viewDidLoad

searchBar.delegate = self

and call this function

    func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.text = ""
    return true
}

Upvotes: 1

Related Questions