Как использовать панель поиска в TableView со свернутыми разделами? - PullRequest
0 голосов
/ 11 июня 2019

Мне нужно использовать панель поиска для фильтрации данных, и при нажатии в результатах поиска она должна быть выбрана в TableView. У меня есть данные, организованные в свернутые разделы.

Я перепробовал почти все, что нашел в интернете, но безрезультатно.

var sveNamirnice = SveSekcije(sekcije: [
    Sekcija(isExpanded: false, nazivSekcije: "Voće", namirnice: [
        Namirnica(naziv: "Jabuke"),
        Namirnica(naziv: "Kruške"),
        Namirnica(naziv: "Banane"),
        Namirnica(naziv: "Jagode"),
        Namirnica(naziv: "Trešnje"),
        Namirnica(naziv: "Višnje"),
        Namirnica(naziv: "Mandarine"),
        Namirnica(naziv: "Pomorandže"),
        Namirnica(naziv: "Limun")
        ]),
    Sekcija(isExpanded: false, nazivSekcije: "Povrće", namirnice: [
        Namirnica(naziv: "Paradajz"),
        Namirnica(naziv: "Krastavac"),
        Namirnica(naziv: "Kupus"),
        Namirnica(naziv: "Krompir"),
        Namirnica(naziv: "Crni luk"),
        Namirnica(naziv: "Crveni luk"),
        Namirnica(naziv: "Beli luk")
        ])
     ])


var selektovaneNamirnice: [String] = []


override func viewDidLoad() {
    super.viewDidLoad()

    SveNamirniceTable.dataSource = self
    SveNamirniceTable.delegate = self


}

@IBOutlet weak var searchNamirnica: UISearchBar!
@IBOutlet weak var SveNamirniceTable: UITableView!



 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let button = UIButton(type: .system)

    button.setTitle(sveNamirnice.sekcije[section].nazivSekcije, for: .normal)


    button.backgroundColor = .orange

    button.layer.borderColor = UIColor.white.cgColor
    button.layer.borderWidth = 0.3

    button.setTitleColor(.white, for: .normal)
    button.setTitleShadowColor(.lightGray, for: .normal)

    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 19)


    button.addTarget(self, action: #selector(handleExpandClose), for: .touchUpInside)
    button.tag = section

    return button

}


@objc func handleExpandClose(button: UIButton) {
    let section = button.tag
    var indexPaths = [IndexPath]()
    for row in sveNamirnice.sekcije[section].namirnice.indices {
        let indexPath = IndexPath(row: row, section: section)
        indexPaths.append(indexPath)
    }


    let isExpanded = sveNamirnice.sekcije[section].isExpanded
    sveNamirnice.sekcije[section].isExpanded = !isExpanded

    if isExpanded {
        SveNamirniceTable.deleteRows(at: indexPaths, with: .fade)
    } else {
        SveNamirniceTable.insertRows(at: indexPaths, with: .fade)
    }
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 45
}

func numberOfSections(in tableView: UITableView) -> Int {

    return sveNamirnice.sekcije.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if !sveNamirnice.sekcije[section].isExpanded {
        return 0
    }

    return sveNamirnice.sekcije[section].namirnice.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let namirnica = sveNamirnice.sekcije[indexPath.section].namirnice[indexPath.row].naziv


    cell.textLabel?.text = namirnica
    // Configure the cell...

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark {
        tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none
        let deselectedCell = tableView.cellForRow(at: indexPath) as UITableViewCell?
        selektovaneNamirnice = selektovaneNamirnice.filter {$0 != deselectedCell?.textLabel?.text}
        tableView.cellForRow(at: indexPath)?.textLabel?.textColor = .black
          tableView.cellForRow(at: indexPath)?.textLabel?.font = .systemFont(ofSize: 17)
        tableView.cellForRow(at: indexPath)?.backgroundColor = .white
        tableView.cellForRow(at: indexPath)?.alpha = 1


    } else {
        tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.checkmark
        selektovaneNamirnice.append(sveNamirnice.sekcije[indexPath.section].namirnice[indexPath.row].naziv)
        tableView.cellForRow(at: indexPath)?.textLabel?.font = .italicSystemFont(ofSize: 17)
        tableView.cellForRow(at: indexPath)?.alpha = 0.7

    tableView.deselectRow(at: indexPath, animated: true)




    print(selektovaneNamirnice)
}

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? SpisakViewController {
        destination.spisakNiz = selektovaneNamirnice
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

}




@IBAction func naSpisak(_ sender: Any) {

    performSegue(withIdentifier: "idiNaSpisak", sender: self)

}

}

Мне нужно отфильтровать данные «namirnice» во всех разделах, и после нажатия на искомый, их нужно выбрать в TableView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...