Выбрать строку других разделов содержит такое же значение в UITableview? - PullRequest
0 голосов
/ 26 июня 2019

У меня есть несколько разделов, и каждый раздел может иметь несколько строк.

Код: Отображать как исключение.

 class SampleViewController: UIViewController {
    let sectionArray = ["pizza", "deep dish pizza", "calzone"]

    let items = [["Margarita", "BBQ Chicken", "Peproni"], ["Margarita", "meat lovers", "veggie lovers"], ["sausage", "chicken pesto", "BBQ Chicken"]]

    @IBOutlet weak var listObj: UITableView!

    var selectedItems = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        registerCell()
        // Do any additional setup after loading the view.
    }
    func registerCell(){
        self.listObj.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }


}
extension SampleViewController : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items[section].count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
         cell.textLabel?.text = items[indexPath.section][indexPath.row]
        if selectedItems.contains(items[indexPath.section][indexPath.row]) {
            print("Selected Item")
            cell.accessoryType = .checkmark
        } else {
            print("Item not selected")
            cell.accessoryType = .none
        }

         return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionArray[section].uppercased()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedItems.append(items[indexPath.section][indexPath.row])
        tableView.reloadData()
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        selectedItems.removeAll { $0 == items[indexPath.section][indexPath.row] }
        tableView.reloadData()
    }
}

Здесь я хочу выбрать строку в раздел , предположим, что раздел Pizza содержит Margarita ряд и пицца с глубоким блюдом также содержит то же значение.Здесь нам нужно выбрать обе строки , которые являются разными разделами.Он должен совпадать с другим разделом, имеющим ту же строку или нет, когда пользователь нажимает на ряды , если совпадает, все строки должны выбрать.

1 Ответ

1 голос
/ 26 июня 2019

Сохранение выбранных имен элементов в массиве и перезагрузка tableview. В методе cellForRowAt проверьте, есть ли в массиве текущий элемент или нет.

var selectedItems = [String]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = items[indexPath.section][indexPath.row]
    if selectedItems.contains(items[indexPath.section][indexPath.row]) {
        print("Selected Item")
    } else {
        print("Item not selected")
    }
    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
      if selectedItems.contains(items[indexPath.section][indexPath.row]) {
        print("Selected Item")
        selectedItems.removeAll { $0 == items[indexPath.section][indexPath.row]
    } else {
        print("Item not selected")
        selectedItems.append(items[indexPath.section][indexPath.row])
    }

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