Ошибка при попытке найти определенную ячейку в табличном представлении Swift - PullRequest
0 голосов
/ 15 мая 2018

Я хочу найти определенный класс ячеек в моем табличном представлении.Я использую следующий код:

func setConfirmEnabledIfNeed(){
        let ip = IndexPath(row: 8, section: 0)
        if let cell = tableView.cellForRow(at: ip) as? ConfirmBtnCell {
            print("find confirm cell")
        }
        let c = tableView.cellForRow(at: ip) as? ConfirmBtnCell
        print("type of cell \(type(of: c))")
    }

print («найти подтверждающую ячейку») никогда не вызывается, однако вывод второй печати: type of cell Optional<ConfirmBtnCell>, что, очевидно, то, что мне нужно.Но почему первая печать не вызывается?

Моя ячейка для строки выглядит так:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let item = viewModel.items[indexPath.row]
    switch item {
    case .selectable(let value, let placeholder, let type):
        let selectionCell = tableView.dequeueReusableCell(withIdentifier: "SelectionCell") as! SelectionCell
        if let placeholder = placeholder { selectionCell.setPlaceholder(placeholder) }
        if let text = value as? String, !text.isEmpty { selectionCell.hidePlaceholder();
            selectionCell.textLbl.text = text }
        if let date = value as? Date { selectionCell.hidePlaceholder();
            selectionCell.textLbl.text = DateFormatterUtil.getReadableStringFromDate(date) }
        return selectionCell
    case .back:
        return tableView.dequeueReusableCell(withIdentifier: "BackBtnCell") as! BackBtnCell
    case .confirm:
        return tableView.dequeueReusableCell(withIdentifier: "ConfirmBtnCell") as! ConfirmBtnCell
    case .editableNumbers(let text, let placeholder, let type):
        let editableCell = tableView.dequeueReusableCell(withIdentifier: "TextEditCell") as! TextEditCell
        editableCell.setup(isNumerical: true)
        if let placeholder = placeholder { editableCell.setPlaceholder(placeholder) }
        if let text = text {editableCell.hidePlaceholder(); editableCell.txtf.text = text }
        editableCell.textChanged = {[weak self] text in
            guard let text = text else { return }
            if type == .sumCash {
                self?.viewModel.collectedInfo[CorrectionChequeViewModel.infoKeys.sumCash.rawValue] = text
                self?.setConfirmEnabledIfNeed()
            }

            if type == .sumElectronic {
                self?.viewModel.collectedInfo[CorrectionChequeViewModel.infoKeys.sumElectronic.rawValue] = text
            }
        }
        return editableCell
    case .editableText(let text, let placeholder, let type):
        let editableCell = tableView.dequeueReusableCell(withIdentifier: "TextEditCell") as! TextEditCell
        editableCell.setup(isNumerical: false)
        if let placeholder = placeholder { editableCell.setPlaceholder(placeholder) }
        if let text = text {editableCell.hidePlaceholder(); editableCell.txtf.text = text }
        editableCell.textChanged = {[weak self] text in
            guard let text = text else { return }
            if type == .sumCash {
                self?.viewModel.collectedInfo[CorrectionChequeViewModel.infoKeys.description.rawValue] = text
            }

            if type == .sumElectronic {
                self?.viewModel.collectedInfo[CorrectionChequeViewModel.infoKeys.number.rawValue] = text
            }
        }
        return editableCell
     default:
        return UITableViewCell()
    }
}

ОБНОВЛЕНИЕ: Я считаю, что код работает, если он не вызывается из метода cellForRow табличного представления.Я попытался запустить этот блок кода с dispatch_after, и он работает.

1 Ответ

0 голосов
/ 15 мая 2018

В вашем операторе if значение tableView.cellForRow(at: ip) as? ConfirmBtnCell равно нулю, поэтому вы никогда не вводите блок.

Во втором операторе (let c = tableView.cellForRow(at: ip) as? ConfirmBtnCell) значение c являетсяOptional<ConfirmBtnCell>.Если вы развернете необязательное значение, вы увидите, что его развернутое значение также равно nil.

Если ваша строка не видна, tableView.cellForRow вернет nil, даже если ячейка установлена.См. Документация Apple .

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