UITableView применяет изменения, сделанные в каждой n-й ячейке - PullRequest
0 голосов
/ 30 января 2020

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

enter image description here

Когда я выбираю ячейку, изображение не отображается.

enter image description here

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

enter image description here

enter image description here

Кто-нибудь знает почему такое происходит и как это исправить?

import UIKit
struct Section {
    let letter : String
    let names : [String]
}
var sections = [Section]()
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
    @IBOutlet weak var table: UITableView!
    var data = ["Alb","bim","ck","Da","Esel","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","spacko","yarr","mom","nun","loser","zebra","jao","ihr","peep","reee","vogel","xylo","uuuf","tiiii","qqqq","m","z","aw","bim","ce","did","Esel","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","fried","spacko","yarrack","mom","nun","loser","zebra","jao","ihr","peep","reee","vogel","xylo","uuuf","tiiii","qqqq","m","z"]
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].names.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        return cell
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].letter
    }
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return sections.map{$0.letter}
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        table.rowHeight = 90.0
        let groupedDictionary = Dictionary(grouping: data, by: {String($0.prefix(1))})
        let keys = groupedDictionary.keys.sorted()
        sections = keys.map{ Section(letter: $0, names: groupedDictionary[$0]!.sorted()) }
        table.reloadData()
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
        cell.checkmark.isHidden = !cell.checkmark.isHidden
    }
}
import UIKit

class TableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBOutlet weak var checkmark: UIImageView!

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Ответы [ 2 ]

1 голос
/ 30 января 2020

Клетки повторно используются в качестве вашего свитка. Вы должны убедиться, что cellForRowAt правильно настраивает ячейку в удаленном состоянии на основе модели данных; ie. если выбрано row, покажите галочку. Если он не выбран, скрыть его.

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

Вы можете использовать набор для отслеживания выбранных строк и проверки их содержимого. при настройке ячейки:

var selectedRows = Set<IndexPath>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    cell.checkmark.isHidden = !self.selectedRows.contains(indexPath)
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if self.selectedRows.contains(indexPath) {
        self.selectedRows.remove(indexPath)
    } else {
        self.selectedRows.insert(indexPath)
    }
    tableView.reloadRows(at:[indexPath], with: .none)
}
0 голосов
/ 30 января 2020

вы можете создать массив массивов, в котором будут храниться значения bool для строк в индексе в зависимости от строк и раздела, и когда вы вносите изменения в любую из строк в любом из разделов, то изменяете значения bool для указанную строку c в разделе spoecifi c, которую вы можете обнаружить в строке didselect, где можно найти то, в каком разделе работает ячейка didselect, и после этого перезагрузите указанную строку c или таблицу и установите значения в соответствии с созданным массивом.

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