如何从项目的collectionView访问选定的单元格? //储存Firebase的物品

时间:2019-12-05 13:21:57

标签: ios swift

我将swift应用程序与Firebase连接起来,现在我正试图从集合视图中获取所选项目的项目密钥,以将所选项目存储到购物车中。

import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage
class ViewController6: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{

    @IBOutlet weak var nextButton: UIButton!


    @IBOutlet weak var itemCollectionView: UICollectionView!
    var customItemFlowLayout: CustomItemFlowLayout!
    var items = [itemsL]()
    //var ind = 0


    var dbRef: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        nextButton.layer.cornerRadius = 10

        dbRef = Database.database().reference().child("items")
        loadDB()

        customItemFlowLayout = CustomItemFlowLayout()
        itemCollectionView.collectionViewLayout = customItemFlowLayout
        //itemCollectionView.backgroundColor = .white

    }

      func loadDB(){
        dbRef.observe(DataEventType.value, with: { (snapshot) in
            var newItems = [itemsL]()


            for itemsLSnapshot in snapshot.children {
                // condition for filtring items
                if itemsL.init(snapshot:  itemsLSnapshot as! DataSnapshot).key >= "2"{


                    // bring item
                    // #######
                let itemsLObject = itemsL(snapshot: itemsLSnapshot as! DataSnapshot)
                newItems.append(itemsLObject)
                    // #######
                }

            }
            self.items = newItems
            self.itemCollectionView.reloadData()
        })
      }

      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
          return items.count
      }

      func collectionView(_ collectionView: UICollectionView, cellForItemAt IndexPath: IndexPath) -> UICollectionViewCell {
          let cell = itemCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: IndexPath) as! ItemCollectionViewCell

          let item = items[IndexPath.row]

            cell.imageView.sd_setImage(with: URL(string: item.url),placeholderImage: UIImage(named: "image22"))
            cell.itemName.text = item.itemName
            cell.price.text = item.price

            cell.layer.borderColor = UIColor.gray.cgColor
            cell.layer.borderWidth = 1

          return cell
      }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderColor = UIColor.blue.cgColor
        cell?.layer.borderWidth = 3
        cell?.isSelected = true
        }


    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderColor = UIColor.gray.cgColor
        cell?.layer.borderWidth = 1
        cell?.isSelected = false
    }
}

items in firebase

1 个答案:

答案 0 :(得分:1)

您的代码选择并取消选择了单元格,但状态不是持久的。

使选择持久化的最可靠方法是在模型中添加属性

struct ItemsL { // please name structs with starting capital letter

    var isSelected = false
    // other properties
}

cellForItemAt中,根据此属性选择单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = itemCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: IndexPath) as! ItemCollectionViewCell

    let item = items[indexPath.row]

    cell.imageView.sd_setImage(with: URL(string: item.url),placeholderImage: UIImage(named: "image22"))
    cell.itemName.text = item.itemName
    cell.price.text = item.price
    if item.isSelected {
       cell.layer.borderColor = UIColor.blue.cgColor
       cell.layer.borderWidth = 3
       cell.isSelected = true
    } else {
       cell.layer.borderColor = UIColor.gray.cgColor
       cell.layer.borderWidth = 1
       cell.isSelected = false
    }
    return cell
}

didSelectItemAt中切换isSelected并重新加载项目,不需要didDeselectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    items[indexPath.row].isSelected.toggle()
    collectionView.reloadItems(at: [indexPath])
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    ....
}  

要获取所选项目,请过滤数组

let selectedItems = items.filter{ $0.isSelected }