Alexey K Alexey K - 2 months ago 14
Swift Question

How to delete item from collection view?

I try to remove item from collectionview based on user choice in alert

I have following code

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.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 = 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")


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

hello world works okay and app crashes when i press delete person

console output is

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'

what am i doing wrong ?

Answer Source

You should change




deleteItemsAtIndexPaths expects an array of NSIndexPaths, not an array of numbers.

Besides that, if you call deleteItemsAtIndexPaths you don't need a call to reloadData - this will even prevent any animation from happening.

Don't forget to update your data source - the person has to be removed from the people array.


Do this before calling deleteItemsAtIndexPaths.