【问题标题】:Deselect from collectionView and cancel item from array从 collectionView 中取消选择并从数组中取消项目
【发布时间】:2016-03-30 20:29:57
【问题描述】:

我有以下代码:

 var selectedIndexPaths = [NSDate]()

    func collectionView(collectionView: UICollectionView,  didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let cell = collectionView.cellForItemAtIndexPath(indexPath) as?  PartExpense

        if cell?.selected == true {
            cell?.layer.borderWidth = 4.0
            cell?.layer.borderColor = UIColor.greenColor().CGColor

            selectedIndexPaths.append(cell!.idPartecipant)

            print(selectedIndexPaths)


        }
    }

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = collectionView.cellForItemAtIndexPath(indexPath)
        if cell?.selected == false {
            cell?.layer.borderColor = UIColor.clearColor().CGColor


            if let index = selectedIndexPaths.indexOf(indexPath.row) {
                selectedIndexPaths.removeAtIndex(index)
                print(selectedIndexPaths)
            }

        }

    }

一切顺利,直到行: if let index = selectedIndexPaths.indexOf(indexPath.row)

这是错误:“无法将 Int 类型的值转换为预期的 NSDate 类型”我该怎么做才能做到这一点?如何转换数组以避免此错误?

【问题讨论】:

    标签: arrays swift uicollectionview


    【解决方案1】:

    您编写的方式是询问该数组中的所有 NSDates 日期“indexPath.row”的索引是什么。错误是说 indexPath.row 是 int 而不是日期。你到底想做什么?

    【讨论】:

    • 我需要将这个特定元素 idPartecipant 放入数组中,该元素是与 coreData 一起存储的 Nsdate。当我取消选择我需要删除元素的行时。
    • 首先通过在原始数据源中搜索数据(cellForItemAtIndexPath中使用的数组)找到取消选择的日期。一旦你有一个被取消选择的然后搜索你 selectedIndexPaths 数组的日期 if let deselectedData:NSDate = dataSouce[indexPath.row] { if let index = selectedIndexPaths.indexOf(deselectedData) { selectedIndexPaths.removeAtIndex(index) } }跨度>
    • 使用您的代码,当我取消选择时有时会收到此错误:“致命错误:索引超出范围”
    • 这意味着你的数学有问题。假设它在索引 2 处寻找 NSDate,但数组中只有 2 个元素。第一个元素位于索引 0,第二个元素位于索引 1。索引 2 中没有任何内容。“致命错误:索引超出范围”。如果我提供帮助,请标记我的答案正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多