Ячейка табличного представления отменяется после первого нажатия. - PullRequest
0 голосов
/ 15 ноября 2018

enter image description here

Gif, изображающий, что:

Когда пользователь выбирает ячейку табличного представления впервые (флажок отмечен впервые), ячейка выбираетсяно после этого он автоматически отменяется, и ничего не происходит, когда я нажимаю второй раз. Но когда я нажимаю в третий раз, ячейка выбирается правильно, а при 4-м касании она отменяется и, соответственно, 5-й и 6-й раз.

Мой метод didSelectRowAt () выглядит следующим образом:

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectRowAt indexPath: IndexPath) {

    let cell = expandableTableView.cellForRow(at: indexPath) as! FilterTableCell

    let dictKey : String = FilterKeysMapping[FilterKeysFront.object(at: indexPath.section) as! String]!

    if(self.FilterDictAPI[dictKey] == nil){
        self.FilterDictAPI[dictKey] = [indexPath.row: self.FilterValueArray.object(at: indexPath.row)]
    }
    else{
        self.FilterDictAPI[dictKey]![indexPath.row] = self.FilterValueArray.object(at: indexPath.row)
    }

    self.expandableTableView.beginUpdates()
    cell.button.isSelected = true
    self.expandableTableView.reloadRows(at: [indexPath], with: .automatic)
    self.expandableTableView.endUpdates()
    expandableTableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
}

didDeselectRowAt () выглядит следующим образом:

   func expandableTableView(_ expandableTableView: LUExpandableTableView, didDeselectRowAt indexPath: IndexPath) {

        print("Did Deselect Cell at section \(indexPath.section) row \(indexPath.row)")
        let cell = expandableTableView.cellForRow(at: indexPath) as! FilterTableCell
        cell.button.isSelected = false        
        let dictKey : String = FilterKeysMapping[FilterKeysFront.object(at: indexPath.section) as! String]!

        if(self.FilterDictAPI[dictKey] != nil){
            self.FilterDictAPI[dictKey]?.removeValue(forKey: indexPath.row)
        }
        print("dict after removing values : \(self.FilterDictAPI)")
    }

Метод cellForRowAt () имеет вид:

   func expandableTableView(_ expandableTableView: LUExpandableTableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = expandableTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? FilterTableCell else {
            assertionFailure("Cell shouldn't be nil")
            return UITableViewCell()
        }
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.label.text = "\(self.FilterValueArray.object(at: indexPath.row))" + "  (" + "\(self.FilterCountArray.object(at: indexPath.row))" + ")"
        return cell
    }

Ячейка табличного представления:

class FilterTableCell: UITableViewCell {

    let label = UILabel()
    let button = UIButton()
    var check = Bool()

    // MARK: - Init

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(label)
        contentView.addSubview(button)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Base Class Overrides

    override func layoutSubviews() {
        super.layoutSubviews()

        label.frame = CGRect(x: 42, y: 0, width: contentView.frame.width-42, height: contentView.frame.height)
        self.label.font = UIFont(name: "PlayfairDisplay-Regular", size: 18)
        button.frame = CGRect(x:10, y: contentView.frame.height/2-8, width: 16, height: 16)
        button.setImage(UIImage(named: "CheckboxUnchecked"), for: .normal)
        button.setImage(UIImage(named: "CheckboxChecked"), for: .selected)
        button.setImage(UIImage(named: "CheckboxUnchecked"), for: .highlighted)
    }

}

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

1 Ответ

0 голосов
/ 15 ноября 2018

Что именно происходит в didSelectRowAt, когда вы перезагружаете этот indexPath, эта ячейка автоматически отменяется, и вызывается метод didDeselectRowAt, где cell.button.isSelected = false убирает галочку.

Итак, чтобы исправить этот комментарийследующие строки в методе didSelectRowAt.

self.expandableTableView.beginUpdates()
self.expandableTableView.reloadRows(at: [indexPath], with: .automatic)
self.expandableTableView.endUpdates()

Кроме того, сбросьте выбранное состояние кнопки в методе prepareForReuse() ячейки.Это исправит неопределенное поведение, когда флажок устанавливается случайно или после первого или второго касания.

override func prepareForReuse() {
    super.prepareForReuse()

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