Предварительный выбор ячеек при загрузке таблицы - PullRequest
0 голосов
/ 04 мая 2020

Я хочу предварительно выбрать ячейки при загрузке таблицы. Я следовал этому ответу, но он не работает должным образом. Не всегда предварительно выбираются правильные ячейки. { ссылка } Выбирает только последнюю ячейку. Как заставить его работать должным образом?

Для Tableview установлено значение Single Selection.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell else {
        fatalError("Can't find cell")
    }

    cell.title = dataSource[indexPath.row]        

    if globalCheckedArray[indexPath.row].checked {
        self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    } else {
        self.tableView.deselectRow(at: indexPath, animated: false)
    }

    return cell
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    globalCheckedArray[indexPath.row].checked = true

    if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
        tableView.deselectRow(at: indexPath, animated: true)
        return nil
    }

    return indexPath
}

func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
    return nil
}

1 Ответ

0 голосов
/ 05 мая 2020

Вам нужно сделать пару вещей ...

  • использовать структуру данных - скорее всего, массив пользовательских объектов - для отслеживания "выбранного" состояния
  • установить .accessoryType для ячейки в cellForRowAt
  • передать массив выбранных строк (выбранных объектов) в контроллер следующего представления

Вот очень простой пример. В свою раскадровку добавьте UITableViewController, установите для его пользовательского класса значение TestTableViewController и вставьте его в UINavigationController.

. При запуске вы можете выбрать, то есть добавить галочки, к нескольким строк.

Когда вы нажмете кнопку «Тест» на панели навигации, вы получите от sh до SampleViewController, что будет отображать выбранные заголовки строк в метке.

Когда вы go «Назад» Ваши данные будут сохранены, а правильные строки будут помечены галочками.

struct MyDataStruct {
    var title: String = ""
    var isSelected: Bool = false
}

class TestTableViewController: UITableViewController {

    var myData: [MyDataStruct] = [
        MyDataStruct(title: "One", isSelected: false),
        MyDataStruct(title: "Two", isSelected: false),
        MyDataStruct(title: "Three", isSelected: false),
        MyDataStruct(title: "Four", isSelected: false),
        MyDataStruct(title: "Five", isSelected: false),
        MyDataStruct(title: "Six", isSelected: false),
        MyDataStruct(title: "Seven", isSelected: false),
        MyDataStruct(title: "Eight", isSelected: false),
        MyDataStruct(title: "Nine", isSelected: false),
        MyDataStruct(title: "Ten", isSelected: false),
        MyDataStruct(title: "Eleven", isSelected: false),
        MyDataStruct(title: "Twelve", isSelected: false),
        MyDataStruct(title: "Thirteen", isSelected: false),
        MyDataStruct(title: "Fourteen", isSelected: false),
        MyDataStruct(title: "Fifteen", isSelected: false),
        MyDataStruct(title: "Sixteen", isSelected: false),
        MyDataStruct(title: "Seventeen", isSelected: false),
        MyDataStruct(title: "Eighteen", isSelected: false),
        MyDataStruct(title: "Nineteen", isSelected: false),
        MyDataStruct(title: "Twenty", isSelected: false),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TableViewCell")

        let b = UIBarButtonItem(title: "Test", style: .plain, target: self, action: #selector(barButtonTapped(_:)))
        self.navigationItem.rightBarButtonItem = b
    }

    @objc func barButtonTapped(_ sender: Any?) -> Void {

        // instantiate the next view controller
        let vc = SampleViewController()

        // filter myData to only the elements with isSelected = true
        let selectedItems = myData.filter{ $0.isSelected == true }

        // set the next VC's property (i.e. pass the data to it)
        vc.theSelectedRows = selectedItems

        // push to the next VC
        self.navigationController?.pushViewController(vc, animated: true)

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath)
        let dataElement: MyDataStruct = myData[indexPath.row]
        cell.textLabel?.text = dataElement.title
        cell.accessoryType = dataElement.isSelected ? .checkmark : .none
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // toggle selected state in data
        myData[indexPath.row].isSelected = !myData[indexPath.row].isSelected
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }

}

class SampleViewController: UIViewController {

    var theSelectedRows: [MyDataStruct] = [MyDataStruct]()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let resultLabel: UILabel = UILabel()
        view.addSubview(resultLabel)
        resultLabel.translatesAutoresizingMaskIntoConstraints = false
        resultLabel.numberOfLines = 0
        var s = ""
        theSelectedRows.forEach { d in
            s += d.title + "\n"
        }
        resultLabel.text = s
        resultLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        resultLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }

}

Вывод:

enter image description here

enter image description here

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