重用集合视图单元的问题

时间:2017-03-02 17:09:56

标签: ios swift uicollectionview

我已经坚持这个问题2天了。我不知道为什么。

我有一个购物车目的的集合视图。可重复使用的单元格上有一个步进器,其中包含 valueChanged 事件。

我使用以下代码来处理问题:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CartCollectionViewCell
    cell.name?.text = cart[indexPath.row].value[0]
    let url = URL(string: (baseUrl + (cart[indexPath.row].value[1])))
    cell.img.setImageWith(url!)
    cell.price?.text = "$" + (cart[indexPath.row].value[2])
    cell.remove.addTarget(self, action: #selector(cartViewController.remove_from_cart(sender:)), for: .touchDown)
    cell.remove.tag = indexPath.row
    cell.qty.value = Double(cart[indexPath.row].value[3])!
    cell.qty.addTarget(self, action: #selector(cartViewController.stepperValueChanged(stepper:)), for: .valueChanged)
    cell.qty.tag = indexPath.row
    return cell
}

func stepperValueChanged(stepper: GMStepper) {
    let pos = stepper.convert(CGPoint.zero, to: collection)
    let indexPath = collection.indexPathForItem(at: pos)!
    let cell: CartCollectionViewCell = collection.cellForItem(at: indexPath) as! CartCollectionViewCell

    if cell.qty != nil {
        let value = String(Int(cell.qty.value))
        var item = cart[indexPath.row]
        item.value[3] = value
        cart[indexPath.row] = item
    }
}

func remove_from_cart(sender: UIButton){
    let pos = sender.convert(CGPoint.zero, to: collection)
    let indexPath = collection.indexPathForItem(at: pos)!
    cart.remove(at: indexPath.row)
    amount = 0.0
    collection.reloadData()
}

滚动集合视图后发生以下错误:

  

"致命错误:在展开可选值时意外发现nil"

let cell: CartCollectionViewCell = collection.cellForItem(at: indexPath) as! CartCollectionViewCell

此行由Xcode突出显示。

0 个答案:

没有答案