Я не смог найти ответ, извините, если об этом уже спрашивали.
У меня есть UICollectionView, и я просто хочу изменить цвет ячейки, по которой щелкнули.
Тем не менее, я получаю очень странное поведение.
У меня есть три предмета, например:
Предположим, что каждая ячейка SELECTED окрашена, а DESELECTED не
Сценарий: 1) Я щелкаю первый элемент: ничего не происходит 2) Я нажимаю первый элемент снова: Теперь он ВЫБРАН 3) Я нажимаю 2-й элемент, он ВЫБРАН, первый изменится на DESELECTED 4) Я снова нажимаю первый, ничего не происходит.5) Первый снова: ВЫБРАН 6) Я щелкаю третий: Первый ДЕСЛЕКТИРОВАННЫЙ
Другой сценарий:
1) Я щелкаю первый элемент: ничего не происходит 2) Я нажимаю второй элемент: 1-йвыбирается
Что здесь происходит?
Мой код:
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
}