首页 > 解决方案 > CollectionView自定义单元格标签在滚动时消失

问题描述

我的 collectionview 有一个自定义单元格,当我向下滚动并再次回到单元格时,单元格中的一个标签会消失。

这是我的cellForItemAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == productCollectionView {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifiers.ProductCell, for: indexPath) as? ProductCell {

if cartProducts.contains(products[indexPath.item]) {
//this is the product
var product = products[indexPath.item]
//get the index from cartProducts
let index = cartProducts.firstIndex(of: product)

//Get the cartcount and update the product
let cartCount: Int = cartProducts[index!].cartCount
product.cartCount = cartCount
products[indexPath.item] = product

//now set the updated product for cell.product
cell.product = products[indexPath.item]
cell.delegate = self
return cell

} else {
cell.product = products[indexPath.item]
cell.delegate = self
return cell
}

} else 
if collectionView == categoryCollectionView{
//...this is another collection and not the collectionView that I have problem with
return cell
}

return UICollectionViewCell()
}
}

这是我在 y 自定义单元格中为当我向下滚动并返回到单元格时消失的标签的内容:

class ProductCell: UICollectionViewCell {
var product: Product!
    {
        didSet {
            commonUIUpdate()
        }
    }

func commonUIUpdate() {
//set the price per amount and its unit
        if product.pricePerAmountExist == true {
            pricePerAmountLbl.isHidden = false
            if let PricePerAmount = formatter.string(from: Double(product.pricePerAmount)/100 as NSNumber) {
                let PricePerAmountVoume = Float(String(Double(product.pricePerAmountVolume)/100))?.clean ?? ""

                pricePerAmountLbl.text = "\(PricePerAmount)/\(String(describing: PricePerAmountVoume))\(product.pricePerAmountUnit)"
            }
        } else
            if product.pricePerAmountExist == false {
                pricePerAmountLbl.isHidden = true
        }
}
}

我在pricePerAmountLbl.isHidden需要时将标签设置为 true 和 false,但我仍然不明白为什么它会消失。当我没有在自定义单元格中为标签设置隐藏状态时,标签的内容会在所有不正确的单元格中重复。

编辑:

我将以下内容添加到单元格但仍然没有成功问题仍然存在

else if product.pricePerAmountExist == false {
    pricePerAmountLbl.isHidden = true
} else {
   pricePerAmountLbl.isHidden = false
}

标签: swiftuitableviewuicollectionviewuicollectionviewcellcustom-cell

解决方案


你没有处理所有的情况。您的标签保持隐藏状态,因为它被设置为隐藏在前一个单元格中。您可能想要更改代码以覆盖丢失的情况。希望能帮助到你:

else if product.pricePerAmountExist == false {
    pricePerAmountLbl.isHidden = true
} else {
   pricePerAmountLbl.isHidden = false
   pricePerAmountLbl.text = "This case was not handled before"
}

推荐阅读