gpt4 book ai didi

ios - 如何防止在 cellForRowAt 中重复相同的代码

转载 作者:行者123 更新时间:2023-11-28 15:06:05 26 4
gpt4 key购买 nike

你能帮我找到一个解决方案,而不是一次又一次地复制相同的代码吗?现在我有了这段代码

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: productImageCell, for: indexPath) as! ProductImageCell
if let product = self.product {
cell.product = product
}
cell.selectionStyle = .none
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: productDetailCell, for: indexPath) as! ProductDetailCell
cell.backgroundColor = UIColor.lightGray
if let product = self.product {
cell.product = product
}
cell.selectionStyle = .none
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: productDeliveryCell, for: indexPath) as! ProductDeliveryTimeCell
cell.selectionStyle = .none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: productDeliveryCell, for: indexPath) as! ProductDeliveryTimeCell
cell.selectionStyle = .none
return cell
}
}

如你所见,我确实一次又一次地复制这部分

    let cell = tableView.dequeueReusableCell(withIdentifier: productImageCell, for: indexPath) as! ProductImageCell
if let product = self.product {
cell.product = product
}
cell.selectionStyle = .none
return cell

我确实尝试过类似的方法,但它不起作用

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

var cell = UITableViewCell()

if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: productImageCell, for: indexPath) as! ProductImageCell
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: productDetailCell, for: indexPath) as! ProductDetailCell
} else if indexPath.row == 2 {
cell = tableView.dequeueReusableCell(withIdentifier: productDeliveryCell, for: indexPath) as! ProductDeliveryTimeCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: productDeliveryCell, for: indexPath) as! ProductDeliveryTimeCell
}

if let product = self.product {
cell.product = product
}
cell.selectionStyle = .none
return cell
}

最佳答案

在所有单元格中包含 product 属性。删除 indexpath.row == 2 block ,它什么都不做。

这样写代码,

if indexPath.row == 1 {
var cell = tableView.dequeueReusableCell(withIdentifier: productImageCell, for: indexPath) as! ProductImageCell
cell.product == "" //clear product field for reusing property
if let product = self.product {
cell.product = product
}
cell.selectionStyle = .none
return cell
} else if .....

关于ios - 如何防止在 cellForRowAt 中重复相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com