移除单元格附件后如何将微调器与单元格内容视图居中?

How to center a spinner with cell content view after removing a cell accessory?

我的情节提要中有一个 table 视图,其中原型单元格默认有一个公开指示器。 当我填充 table 时,我只想从最后一个单元格中删除指示器并将微调器居中放置在其上。 我是这样做的:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterCell", for: indexPath) as! CharacterCell
        
        if indexPath.row == charactersViewModel.charactersCount - 1 {
            cell.accessoryType = .none
            cell.accessoryView = .none
            
            // Spinner
            let spinner = UIActivityIndicatorView(style: .large)
            spinner.color = .white
            spinner.center = cell.contentView.center
            cell.contentView.addSubview(spinner)
            spinner.startAnimating()
        }
        return cell
    }

问题是旋转器偏心了,有点偏左,就像配件还在,只是隐藏了一样。

我觉得我可能错过了一个 table 单元格的生命周期,也许当附件还在时它正在获取内容视图的中心值,所以当它被移除时它是偏离中心的?

我也试过 willDisplay,但同样的事情发生了。

对此有什么建议吗?

如@Paulw11 所述,我使用了第二个子类并在我的 table 视图中创建了另一个单元格原型。

然后当到达 table 的最后一个位置时,我们可以在 cellForRowAt 上使用第二个原型。

情况如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row >= charactersViewModel.charactersCount - 1 {
            reloadRows(indexPath: indexPath)
            let cell = tableView.dequeueReusableCell(withIdentifier: "LoadingCharacterCell", for: indexPath) as! LoadingCharacterCell
            cell.startSpinner()
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterCell", for: indexPath) as! CharacterCell
            cell.configureCell(charactersViewModel: charactersViewModel, cell: cell, index: indexPath.row)
            return cell
        }
    }

private func reloadRows(indexPath: IndexPath) {
        var indexPathList = [IndexPath]()
        indexPathList.append(indexPath)
        charactersTableView.reloadRows(at: indexPathList, with: .automatic)
}

并且使用 reloadRows 函数,当 table 接收到更多数据时更新并删除最后一个单元格。