Установите / снимите флажок внутри ячейки табличного представления с функцией поиска - PullRequest
0 голосов
/ 06 августа 2020

Привет, я новичок в быстром языке и пытаюсь реализовать флажок в виде таблицы с функцией поиска. Но мой код не работает должным образом, не знаю почему. Я хочу, чтобы, если мы поставим / снимем отметку с одного поля, он останется отмеченным / не отмеченным, пока мы снова не нажмем на него. Строка поиска также должна отображать отмеченную / не отмеченную кнопку, а также кнопка, проверенная с помощью поиска, остается отмеченной в списке основных таблиц.

вот мой код контроллера представления -

import UIKit

class ViewController: UIViewController {
    
    var names : [String] = ["Aaran", "Aaren", "Aarez", "Aarman", "Aaron", "Aaron-James", "Aarron", "Aaryan", "Aaryn", "Aayan", "Aazaan", "Abaan", "Abbas", "Abdallah", "Abdalroof", "Abdihakim"]
    var filteredNames : [String] = []
    let searchBar = UISearchController(searchResultsController: nil)
    var checkArray : NSMutableArray = NSMutableArray()
    var userName : NSMutableArray = NSMutableArray()
    var text: String?
    var indexOfSelectedItem: Int?
    

    @IBOutlet weak var tblView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()
        
        filteredNames = names
        self.navigationItem.title = "Contacts"
        self.navigationController?.navigationBar.prefersLargeTitles = true
        searchBar.searchResultsUpdater = self
        searchBar.obscuresBackgroundDuringPresentation = false
        searchBar.searchBar.placeholder = "Search Names"
        navigationItem.searchController = searchBar
        searchBar.searchBar.delegate = self
//        definesPresentationContext = true
//        searchBar.delegate = self
        
        
        self.userName.removeAllObjects()
        for items in names {
            print(items)
            let model = RNCheckedModel()
            model.user_name = items
            model.is_check = false
            self.userName.add(model)
        }
    }
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (searchBar.isActive) {
            return filteredNames.count
        } else {
            filteredNames = names
            return names.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tblCell", for: indexPath) as! TableViewCell
        
        if (searchBar.isActive) {
            
            cell.lblCell.text = filteredNames[indexPath.row]
            let model = self.userName[indexPath.row] as! RNCheckedModel
            if (model.is_check) {
                cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_black_18pt_1x"), for: .normal)
            }
            else {
                cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_outline_blank_black_18pt_1x"), for: .normal)
            }
            cell.btnChck.addTarget(self, action: #selector(self.btnCheck(_:)), for: .touchUpInside)
            return cell
        }
            
        else {
            let model = self.userName[indexPath.row] as! RNCheckedModel
            cell.lblCell.text = model.user_name
            if (model.is_check) {
                cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_black_18pt_1x"), for: .normal)
            }
            else {
                cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_outline_blank_black_18pt_1x"), for: .normal)
            }
//              cell.btnChck.tag = text
//                cell.btnChck.tag = indexPath.row
            cell.btnChck.addTarget(self, action: #selector(self.btnCheck(_:)), for: .touchUpInside)
            cell.btnChck.isUserInteractionEnabled = true
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        ind = indexPath.row
        let getText = tblView.cellForRow(at: indexPath) as! TableViewCell
        text = (getText.lblCell.text!)
        indexOfSelectedItem = names.firstIndex(of: text!)
        print(text!)
        print(indexOfSelectedItem!)
    }
}
extension ViewController: UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate{
    func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        let newString =  (searchBar.text! as NSString).replacingCharacters(in: range, with: text)
        filteredNames = names.filter { $0.lowercased().contains(newString.lowercased()) }
//        filteredNames = names.filter({$0.lowercased().prefix(searchBar.text!.count) == searchBar.text!.lowercased()})

        if newString == ""{
            filteredNames = names
        }
        self.tblView.reloadData()
        return true
    }
  
    
    func updateSearchResults(for searchController: UISearchController) {
        
        self.tblView.reloadData()
    }
    
    @objc func btnCheck(_ sender: UIButton) {
        
        //        let tag = ind
        let tag = indexOfSelectedItem
        let indexPath = IndexPath(row: tag!, section: 0)
        let cell: TableViewCell = tblView.dequeueReusableCell(withIdentifier: "tblCell", for: indexPath) as! TableViewCell
        let model = self.userName[tag!] as! RNCheckedModel
        
        if (model.is_check) {
            model.is_check = false
            cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_outline_blank_black_18pt_1x"), for: .normal)
            checkArray.remove(model.user_name)
        }
        else {
            model.is_check = true
            cell.btnChck.setImage(#imageLiteral(resourceName: "baseline_check_box_black_18pt_1x"), for: .normal)
            checkArray.add(model.user_name)
        }
        self.tblView.reloadData()
    }
}
...