TableView отображает те же элементы, отфильтрованные массивом, даже если элементы массива не отфильтрованы

#swift

#swift

Вопрос:

введите описание изображения здесь у меня есть 2 кнопки и два элемента списка массива, в которых отображаются названия фруктов и цвет фруктов. Я реализовал функцию поиска для поиска фруктов и цветов. Проблема здесь в том

  1. Нажатие на 1-ю кнопку показывает названия фруктов в tableview.
  2. Отфильтровал фрукт по имени. Он возвращает плод обратно
  3. Теперь нажмите за пределами tableview. Он отклоняет tableview
  4. Нажмите на вторую кнопку цвет фруктов.

Возникает проблема. Он показывает первые элементы массива с тем же ключевым словом поиска, которое я ввел в предыдущем поиске. Вот мой код и снимки экрана для справки. Где мне нужно изменить код. Любая помощь приветствуется.

 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()
    }
}

 

Ответ №1:

попробуй вот это

 lazy var searchBar:UISearchBar = UISearchBar()
 

в viewDidLoad

 searchBar.delegate = self
 

и вызовите эту функцию

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