UICollectionViewCell着色不符合预期

时间:2018-12-08 15:16:49

标签: swift uicollectionviewcell highlight collectionview

我找不到答案,对不起,如果以前有人问过。

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

但是,我的行为很奇怪。

我有三个项目,像这样:

enter image description here

假设每个SELECTED单元格都是彩色的,而DESELECTED则不是

场景: 1)我点击第一个项目:什么也没有发生 2)我再次单击第一项:现在已选择 3)我单击第二项,它已被选中,第一个变为DESELECTED 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
}

1 个答案:

答案 0 :(得分:1)

向您的var isMarked: Bool = false 类添加新属性

cellForItemAt

首先将此代码添加到cell.backgroundColor = prodInCell.isMarked ? UIColor.green : UIColor.clear cell.layer.borderColor = prodInCell.isMarked ? UIColor.yellow.cgColor : UIColor.black.cgColor 数据源方法

didSelectItemAt

然后在CollectionView toogle的委托方法isMarked中将所选项目的func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { ... products[prodForPurchaseID].toogle() collectionView.reloadData() ... } 属性的值并在集合视图中重新加载数据

Sub FindRow1()
Dim t As Range
Dim c As Range
Dim d As Range
Dim e As Range
Dim f As Range
Dim g As Range
Dim h As Range
Dim i As Range
Dim j As Range
Dim k As Range
Dim l As Range
Dim m As Range
Dim n As Range
Dim o As Range
Dim p As Range
Dim x As Integer
Dim y As Integer


With Worksheets("Recap Sheet").Cells
Set t = .Find("Year of Tax Return", After:=.Range("A1"), 
LookIn:=xlValues).Cells
Set c = .Find("12. Total Gross Annual Cash Flow", 
After:=.Range("A1"), LookIn:=xlValues).Cells
Set d = .Find("15. Total Annual Cash Flow Available to 
Service Debt", After:=.Range("A1"), LookIn:=xlValues)
Set e = Range(t.Offset(1, 0), c.Offset(-1, 0))
Set f = Range(c.Offset(1, 0), d.Offset(-1, 0))
Set i = Range(t.Offset(1, 9), c.Offset(-1, 9))
Set j = Range(c.Offset(1, 9), d.Offset(-1, 9))
Set k = Range(t.Offset(-1, 9), d.Offset(0, 10))
Set l = Range(t.Offset(1, 9), d.Offset(0, 9))
Set m = Range(t.Offset(1, 10), d.Offset(0, 10))
Set n = Range(d.Offset(0, 9), d.Offset(0, 10))
Set o = Range(c.Offset(0, 9), c.Offset(0, 10))
Set p = Range(t.Offset(0, 9), t.Offset(0, 10))
Set g = c.Offset(0, 9).Cells
Set h = d.Offset(0, 9).Cells