首页 > 解决方案 > Swift 中奇怪的协议行为

问题描述

我的应用程序中有一个协议:

public protocol ViewModel {}

public protocol ConfigurableView where Self: UIView {   
    func configure(with viewModel: ViewModel) 
}

显然,这样做的目的是标准化我的 ViewModel 方法。

当我在 cellForRowAt: 方法中应用配置调用时:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellType(for: indexPath).reuseIdentifier, for: indexPath)

    let item = sections[indexPath.section][indexPath.item]
    let viewModel = process(item: item)

    (cell as? ConfigurableCell)?.configure(item:item)

    return cell

}

我看到了奇怪的行为 - 本质上,单元格的类型是正确的,并且在此方法中具有我期望的属性,但是一旦将其传递到 configure 方法中,其所有自定义属性(UILabels 等)都为零。这就像它复制了单元格而不转移所有属性。一旦代码进入配置方法的内部,它就完全是一个不同的指针。

我在这里想念什么?我试过在操场上重新创建它,但我做不到,这让我怀疑出队细胞很奇怪。

标签: iosswiftprotocols

解决方案


推荐阅读