Delete Items from Collection View Controller iOS Tutorial
source link: https://www.tuicool.com/articles/hit/2amEZrj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Items inside a Collection View can be manipulated by modifying the connected model data. In this tutorial items will be removed from the Collection View Controller. This tutorial is made with Xcode 10 and built for iOS 12.
Project Setup
Open Xcode and create a new Single View App.
For product name, use IOSDeleteItemsCollectionViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Storyboard Setup
Go to the storyboard . Remove the View Controller from the Storyboard and drag a Collection ViewController to the Scene . Select the View Controller and go to the Editor Menu. Select Embed In -> Navigation Controller.
Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Collection View Cell and go to the Attribute inspector. In the View section change the Background color to Light Gray Color.
Select The Collection View and go the Size inspector. In the Collection View section change the Cell Size to a width and height of 100 points.
Drag a Label from the Object Library and place it on the Center of the Collection View Cell.
Drag another Label to the right-bottom of the cell. This label will be needed for the state of the selection during edit mode, when selected a checkmark will be displayed. Select the label and go to the Attribute inspector. In the Label section delete the label text so the label will contain an empty string.
Select the Collection View Cell and go to the Atrribute inspector. In the Collection Reusable View section set the Identifier to "Cell".
Next, drag a Bar Button Item to the right side of the Navigation Bar. Select the Bar Button Item and go to the Attributes inspector. In the Bar Button Item section change the System Item to Trash. Also in the Bar Item section deselect the Enabled checkbox. The trash button will only be displayed when an item is selected in edit mode.
The storyboard will look like this.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS -> Source -> Cocoa Touch Class. Name it CollectionViewController and make it a subclass of UICollectionViewController.
The CollectionViewController class needs to be linked to The Collection View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to CollectionViewController
Custom Collection View Cell
Select File -> New File -> iOS -> Source -> Cocoa Touch Class. Name the class CollectionViewCell and make it a subclass of UICollectionViewCell.
Go back to Main.storyboard and select the Collection View Cell. Go to the Identity inspector and in the Custom Class section change the class to CollectionViewCell .
Outlet an Action Connections
Select the Assistant Editor and make sure the CollectionViewCell.swift file is visible. Ctrl and drag from the Title Label to the CollectionViewCell class and create the following Outlet.
Ctrl and drag from the Checkmark Label to the CollectionViewCell class and create the following Outlet.
Make sure the CollectionViewController.swift file is visible. Ctrl and drag from the trash bar button item to the CollectionViewController class and create the following Outlet.
Ctrl and drag from the trash bar button item to the CollectionViewController class and create the following Action.
Code Implementation
Go to CollectionViewController.swift file and enter the following line.
var modelData = ["One","Two","Three","Four","Five"]
Since the Reuse Identifier is defined in the Storyboard, the following line can be removed in the CollectionViewController class
// Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
With the creation of the CollectionViewController class, most delegate methods are already implemented. Some methods must be tweaked a little. Change the following methods.
override func numberOfSections(in collectionView: UICollectionView) -> Int { // 1 return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 2 return modelData.count } override func collectionView(_ collectionView: UICollectionView, cell override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 3 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell cell.titleLabel.text = modelData[indexPath.row] return cell }
-
By default the CollectionView only has 1 section.
-
The number of cells is equal to the number of items in the modelData array.
-
The text of the label is set to the current index of the modelData array.
Change the viewDidLoad method to
override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem }
The Edit Bar Button Item is added to the Navigation Bar. This can be used to toggle to Edit mode.
Build and Runthe project.
Implement Editing Mode
Go to the CollectionViewCell.swift file and add two methods.
// 1 var isInEditingMode: Bool = false { didSet { checkmarkLabel.isHidden = !isInEditingMode } } // 2 override var isSelected: Bool { didSet { if isInEditingMode { checkmarkLabel.text = isSelected ? "✓" : "" } } }
-
A Property Observer is created which will toggle the visibility of the checkmark label according if the coillection view controller is in editing mode or not.
-
Another property observer is created which will display/remove the checkmark when the cell is selected or not.
Next, go to the CollectionViewController.swift file and add the setEditing(_:animated) method
override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) collectionView.allowsMultipleSelection = editing let indexPaths = collectionView.indexPathsForVisibleItems for indexPath in indexPaths { let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell cell.isInEditingMode = editing } }
This method will check if a cell is in editing mode. Next add the following two methods.
// 1 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if !isEditing { deleteButton.isEnabled = false } else { deleteButton.isEnabled = true } } // 2 override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let selectedItems = collectionView.indexPathsForSelectedItems, selectedItems.count == 0 { deleteButton.isEnabled = false } }
-
If a cell is selected the trash icon is displayed, otherwise it remains hidden
-
if an cell is deselected and there are no other cells selected the trash icon is hidden.
Add the following line before the return cell line in the collectionView(_:didSelectItemAt) method
cell.isInEditingMode = isEditing
Again, this will check if a cell is in editing mode. Everything is now in place for the edtitng fucntionality. Now the actual deletion can be implemented.
Delete Items
Implement the deleteItem(_:) Action method
@IBAction func deleteItem(_ sender: Any) { if let selectedCells = collectionView.indexPathsForSelectedItems { // 1 let items = selectedCells.map { $0.item }.sorted().reversed() // 2 for item in items { modelData.remove(at: item) } // 3 collectionView.deleteItems(at: selectedCells) deleteButton.isEnabled = false } }
-
The selected cells will be reversed and sorted so the items with the highest index will be removed first.
-
the items will be removed from the modelData array
-
The selected cells will be deleted from the Collection View Controller and the trash icon will be disabled.
Run Project
Build and Runthe project and select the Edit Button. Select a few cells and press the Trash button to remove the items.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK