CollectionView 自定义单元格标签在滚动时消失

CollectionView Custom cell Label Disappears on Scroll

我的 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
}

您并未处理所有案件。您的标签保持隐藏状态,因为它在前一个单元格中设置为隐藏。您可能想要更改代码以弥补缺失的情况。希望对您有所帮助:

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

我的代码没有任何问题!错误发生在情节提要中。我的标签存储在一个堆栈视图中,而那个堆栈视图存储在另一个堆栈视图中;当我滚动并且标签会隐藏时,stackview 高度会变为零并且即使我取消隐藏标签它也保持为零。