【问题标题】:How to delete item from collection view?如何从集合视图中删除项目?
【发布时间】:2015-07-18 10:45:30
【问题描述】:

我尝试根据用户在警报中的选择从集合视图中删除一个项目。

我有以下代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let person = people[indexPath.item]

    let questionController = UIAlertController(title: "What u wanna do?", message: nil, preferredStyle: .Alert)
    questionController.addAction(UIAlertAction(title: "Rename person", style: .Default, handler: {

        (action:UIAlertAction!) -> Void in

        let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert)
        ac.addTextFieldWithConfigurationHandler(nil)

        ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
            let newName = ac.textFields![0] as! UITextField
            person.name = newName.text

            self.collectionView.reloadData() })

        self.presentViewController(ac, animated: true, completion: nil)

    }))

    questionController.addAction(UIAlertAction(title: "Delete Person", style: .Default, handler: {

        (action:UIAlertAction!) -> Void in

        println("hello world")
        self.collectionView.deleteItemsAtIndexPaths([indexPath.item])
        self.collectionView.reloadData()

    }))

    presentViewController(questionController, animated: true, completion: nil)
}

“hello world”运行正常,但当我按“删除人员”时应用程序崩溃。

控制台输出是

hello world
2015-07-18 13:40:14.628 Project10[15888:1274436] -[__NSCFNumber section]:         unrecognized selector sent to instance 0xb000000000000003
2015-07-18 13:40:14.636 Project10[15888:1274436] *** Terminating app due to    uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber    section]: unrecognized selector sent to instance 0xb000000000000003'

我做错了什么?

【问题讨论】:

    标签: swift uicollectionview


    【解决方案1】:

    你应该改变

    self.collectionView.deleteItemsAtIndexPaths([indexPath.item])
    

    self.collectionView.deleteItemsAtIndexPaths([indexPath])
    

    deleteItemsAtIndexPaths 需要 NSIndexPaths 的数组,而不是数字数组。

    此外,如果您调用 deleteItemsAtIndexPaths,则无需调用 reloadData - 这甚至会阻止任何动画的发生。

    不要忘记更新您的数据源 - 必须从 people 数组中删除此人。

    people.removeAtIndex(indexPath.item)
    

    在调用deleteItemsAtIndexPaths之前执行此操作。

    【讨论】:

    • 没有帮助终止应用程序由于未捕获的异常'NSInternalInconsistencyException',原因:'无效更新:第0节中的项目数无效。更新后现有节中包含的项目数(1)必须等于更新前该节中包含的项目数 (1),加上或减去从该节插入或删除的项目数(0 插入,1 删除),加上或减去移入或移出的项目数该部分(0 移入,0 移出)。'
    • 不要忘记更新您的数据源 - 必须从 people 数组中删除此人。
    • 抱歉,我是 swift 的新手 - 如何更新数据源?
    • 我在 self.collectionView.deleteItemsAtIndexPaths([indexPath]) 之后添加了 self.people.removeAtIndex(indexPath.item) 但它仍然崩溃并出现同样的错误
    • 您需要之前完成。抱歉,如果不清楚。
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多