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

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

我有以下代码

  1. func collectionView(collectionView: UICollectionView,didSelectItemAtIndexPath indexPath: NSIndexPath) {
  2. let person = people[indexPath.item]
  3.  
  4. let questionController = UIAlertController(title: "What u wanna do?",message: nil,preferredStyle: .Alert)
  5. questionController.addAction(UIAlertAction(title: "Rename person",style: .Default,handler: {
  6.  
  7. (action:UIAlertAction!) -> Void in
  8.  
  9. let ac = UIAlertController(title: "Rename person",preferredStyle: .Alert)
  10. ac.addTextFieldWithConfigurationHandler(nil)
  11.  
  12. ac.addAction(UIAlertAction(title: "Cancel",style: .Cancel,handler: nil))
  13. ac.addAction(UIAlertAction(title: "OK",style: .Default) { [unowned self,ac] _ in
  14. let newName = ac.textFields![0] as! UITextField
  15. person.name = newName.text
  16.  
  17. self.collectionView.reloadData() })
  18.  
  19. self.presentViewController(ac,animated: true,completion: nil)
  20.  
  21. }))
  22.  
  23. questionController.addAction(UIAlertAction(title: "Delete Person",handler: {
  24.  
  25. (action:UIAlertAction!) -> Void in
  26.  
  27. println("hello world")
  28. self.collectionView.deleteItemsAtIndexPaths([indexPath.item])
  29. self.collectionView.reloadData()
  30.  
  31. }))
  32.  
  33. presentViewController(questionController,completion: nil)
  34. }

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

控制台输出

  1. hello world
  2. 2015-07-18 13:40:14.628 Project10[15888:1274436] -[__NSCFNumber section]: unrecognized selector sent to instance 0xb000000000000003
  3. 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'

我究竟做错了什么 ?

你应该改变
  1. self.collectionView.deleteItemsAtIndexPaths([indexPath.item])

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

deleteItemsAtIndexPaths需要一个NSIndexPaths数组,而不是数组.

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

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

  1. people.removeAtIndex(indexPath.item)

调用deleteItemsAtIndexPaths之前执行此操作.

猜你在找的Swift相关文章