如何从集合视图中删除项目?

How to delete item from collection view?

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

我有以下代码:

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" 工作正常,但当我按 "Delete Person" 时应用程序崩溃。

控制台输出为

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'

我做错了什么?

你应该改变

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

self.collectionView.deleteItemsAtIndexPaths([indexPath])

deleteItemsAtIndexPaths 需要 NSIndexPath 数组,而不是数字数组。

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

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

people.removeAtIndex(indexPath.item)

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