Swift UICollectionViewCell颜色不符合预期

Swift UICollectionViewCell颜色不符合预期,swift,uicollectionviewcell,highlight,collectionview,Swift,Uicollectionviewcell,Highlight,Collectionview,我找不到答案,如果以前有人问过,很抱歉 我有一个UICollectionView,我只想更改单击单元格的颜色 然而,我有一种非常奇怪的行为 我有三个项目,如下所示: 假设每个选定的单元格都有颜色,而取消选定的单元格没有颜色 情景: 1) 我点击第一项:什么也没发生 2) 我再次单击第一个项目:它现在处于选中状态 3) 我点击第二项,它被选中,第一项变为取消选中 4) 我再次点击第一个,什么也没发生。 5) 再次显示第一个:已选定 6) 单击第三个:取消选择第一个 另一种情况: 1) 我点击第一

我找不到答案,如果以前有人问过,很抱歉

我有一个UICollectionView,我只想更改单击单元格的颜色

然而,我有一种非常奇怪的行为

我有三个项目,如下所示:

假设每个选定的单元格都有颜色,而取消选定的单元格没有颜色

情景: 1) 我点击第一项:什么也没发生 2) 我再次单击第一个项目:它现在处于选中状态 3) 我点击第二项,它被选中,第一项变为取消选中 4) 我再次点击第一个,什么也没发生。 5) 再次显示第一个:已选定 6) 单击第三个:取消选择第一个

另一种情况:

1) 我点击第一项:什么也没发生 2) 我单击第二项:第一项被选中

这是怎么回事

我的代码:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        // Display selected Item

        let prodForPurchaseID = products[indexPath.row].getUniqueID()
        let prodForPurchasePrice = products[indexPath.row].getPrice()

        if (m_productsToPurchaseList[prodForPurchaseID] != nil)
        {
            // Product already marked for purchase. Need to remove it from purchase
            changeCellColor(isMarkedAlready: true, didSelectItemAt: indexPath)
            m_productsToPurchaseList.removeValue(forKey: prodForPurchaseID)
        }
        else
        {
            // Product not yet marked for purchase. Need to add it for purchase
            changeCellColor(isMarkedAlready: false, didSelectItemAt: indexPath)
            m_productsToPurchaseList[prodForPurchaseID] = prodForPurchasePrice
        }
    }

    func changeCellColor(isMarkedAlready: Bool, didSelectItemAt indexPath: IndexPath)
    {
        let cell = ProductsCollection.cellForItem(at: indexPath)

        if(isMarkedAlready)
        {
            // Need to unmark cell
            cell?.backgroundColor = UIColor.clear
            cell?.layer.borderColor = UIColor.black.cgColor
        }
        else
        {
            // Need to highlight cell
            cell?.backgroundColor = UIColor.green
            cell?.layer.borderColor = UIColor.yellow.cgColor
        }
    }
我的产品类别:

class Product: NSObject
{
    private var m_Name:String
    private var m_Price: Double
    private var m_Currency: String
    private var m_Description: String
    private var m_Location: String
    private var m_PicturesURLs: [String]
    private var m_OwnerID: String
    private var m_OwnerDisplayName: String
    //private var m_Amount: Int
    private var m_CategoryID: String
    private var m_Category: String
    private var m_SaleTime: String?
    private var m_ProductStatus: String
    public var urlStr: String?
    private var ID: String


    public static let NEW_STATUS = "New"


    init(name: String, price: Double, currency: String, description: String?, location: String, ownerID: String, ownerName: String, uniqueID: String, mainImageURL: String?, category: String!)
    {
        m_Name = name
        m_Price = price
        m_Currency = currency
        m_Category = category
        m_Description = ""
        if let description = description
        {
            m_Description = description
        }
        m_Location = location
        //m_Amount = amount?
        m_ProductStatus = Product.NEW_STATUS
        if (uniqueID == "")
        {
            ID = NSUUID().uuidString
        }
        else
        {
            ID = uniqueID
        }

        m_PicturesURLs = [String]()

        m_OwnerID = ownerID
        m_OwnerDisplayName = ownerName
        m_CategoryID = "cat id"

        if let mainImageURL = mainImageURL
        {
            m_PicturesURLs.append(mainImageURL)
        }
    }


    public func setUrlStr(str: String)
    {
        urlStr = str
    }

    public func getCategoryID() -> String
    {
        return m_CategoryID
    }

    public func getCategory() -> String
    {
        return m_Category
    }

    public func getCurrency() -> String
    {
        return m_Currency
    }

    public func getLocation() -> String
    {
        return m_Location
    }

    public func getSaleTime() -> String?
    {
        return m_SaleTime
    }

    public func getProductStatus() -> String
    {
        return m_ProductStatus
    }

    public func getUniqueID() -> String
    {
        return ID
    }

    public func getName() -> String
    {
        return m_Name
    }

    public func getPrice() -> Double
    {
        return m_Price
    }

    public func getDescription() -> String
    {
        return m_Description
    }

    public func getImages() -> [String]
    {
        return m_PicturesURLs
    }

    public func getOwnerID() -> String
    {
        return m_OwnerID
    }

    public func getOwnerName() -> String
    {
        return m_OwnerDisplayName
    }

    public func AddImageURLToProduct(URL url: String)
    {
        m_PicturesURLs.append(url)
    }

    public func getMainImageURLString() -> String
    {
        if let mainImageURL = m_PicturesURLs.first
        {
            return mainImageURL
        }
        return ""
    }

    public func getNumberOfImages() -> Int
    {
        return m_PicturesURLs.count
    }
}
CellForItemAt函数:

func createCollectionViewCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "product_collection_cell", for: indexPath) as! ProductsCollectionViewCell
    cell.ProductImageView.image = nil
    cell.ProductName.text = nil
    cell.ProductPrice.text = nil
    cell.productUniqueID = nil

    let prodInCell =  searchActive ? filtered[indexPath.row] : products[indexPath.row]

    let prodID = prodInCell.getUniqueID()
    cell.contentMode = .scaleAspectFit

    if let str = prodInCell.urlStr
    {
        cell.ProductImageView.sd_setImage(with: URL(string:str), placeholderImage: #imageLiteral(resourceName: "DefaultProductImage"))
    }
    else
    {
        let dbRef = Storage.storage().reference().child(prodID).child("pic0.jpg")
        cell.contentMode = .scaleAspectFit
        cell.ProductImageView.image = #imageLiteral(resourceName: "DefaultProductImage")
        dbRef.downloadURL(completion:
            {
                url, error in
                if let error = error
                {
                    Constants.logger.error(error)
                }
                else if let url = url
                {
                    prodInCell.setUrlStr(str: url.absoluteString)  // store for upcoming need
                    cell.ProductImageView.sd_setImage(with: URL(string:url.absoluteString), placeholderImage: #imageLiteral(resourceName: "DefaultProductImage"))
                    cell.ProductImageView.contentMode = UIViewContentMode.scaleToFill
                    cell.layoutIfNeeded()
                }
        })

    }
    cell.ProductImageView.clipsToBounds = true
    cell.ProductName.text = prodInCell.getName()
    cell.ProductPrice.text = String(prodInCell.getPrice())
    cell.productUniqueID = prodInCell.getUniqueID()
    return cell
}

将新属性添加到
产品

var isMarked: Bool = false
首先将此代码添加到
cellForItemAt
数据源方法中

cell.backgroundColor = prodInCell.isMarked ? UIColor.green : UIColor.clear
cell.layer.borderColor = prodInCell.isMarked ? UIColor.yellow.cgColor : UIColor.black.cgColor
然后在CollectionView
didSelectItemAt
delegate method
toogle
中标记所选项目的属性值,并在collection view中重新加载数据

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    ...
    products[prodForPurchaseID].toogle()
    collectionView.reloadData()
    ...
}

你能添加Product struct/class吗?添加了@RobertDreslerth这确实帮助我改进了我的代码,所以谢谢:)但这并没有解决问题还有其他想法吗?@Ofri你在更改单元格颜色之前调用
toogle()
吗?是的,我以前切换过这个,但我几乎看不出这能解决我的问题。。。我可以点击单元格A,它将切换单元格B。。。这是我最初的错误:)@Ofri将
cellForItemAt
数据源方法添加到您的问题中