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

前端之家收集整理的这篇文章主要介绍了swift – 如何从集合视图中删除项目?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试根据用户在alert中的选择从collectionview中删除项目

我有以下代码

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",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",handler: {

        (action:UIAlertAction!) -> Void in

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

    }))

    presentViewController(questionController,completion: nil)
}

当我按删除人员时,你好世界工作正常和应用程序崩溃

控制台输出

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需要一个NSIndexPaths数组,而不是数组.

除此之外,如果你调用deleteItemsAtIndexPaths,你不需要调用reloadData – 这甚至可以防止任何动画发生.

不要忘记更新数据源 – 必须从人员阵列中删除此人.

people.removeAtIndex(indexPath.item)

调用deleteItemsAtIndexPaths之前执行此操作.

原文链接:https://www.f2er.com/swift/319244.html

猜你在找的Swift相关文章