38

Add Items to Collection View Controller iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/FriQRfe
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 a new item will be added to 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.

mM3mEju.png!web

For product name, use IOSAddItemsCollectionViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

BB7Jnav.png!web

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.

vI7bqyQ.png!web

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.

6Z7zYfB.png!web

Drag a Label from the Object Library and place it on the Center of the Collection View Cell.

B7JN3mb.png!web

Select the Label and go to the Attribute inspector. In the View section set the Tag value to 100.

Iba2Q3F.png!web

Select the Collection View Cell and go to the Atrribute inspector. In the Collection Reusable View section set the Identifier to "Cell".

fq6ZzqZ.png!web

The storyboard will look like this.

Q3iMbe7.png!web

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.

QNZz6nU.png!web

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

BFVz63A.png!web

Code Implementation

Go to CollectionViewController.swift file and enter the following line.

var modelData = ["Oliver","Harry","George","Jack","Noah"]

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, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    
        // Configure the cell
        // 3
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = modelData[indexPath.row]
        }
    
        return cell
    }
  1. By default the CollectionView only has 1 section.

  2. The number of cells is equal to the number of items in the modelData array.

  3. The text of the label is set to the current index of the modelData array.

Build and Runthe project.

fUNBnyi.png!web

Add Items

Go to the Storyboard and drag a Right Bar Button Item to right side of the Navigation Bar of the Collection View Controller. Select the Bar Button Item and go to the Attributes inspector. Change the Custom Item Value to Add in the Bar Button Item section.

BryYziN.png!web

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl-click and drag from the Bar Button Item to the CollectionViewController class and create the following action

aERJJ3z.png!web

implement the addItem(_:) method

@IBAction func addItem(_ sender: Any) {
    let name = "John"
    modelData.append(name)
    let indexPath = IndexPath(row: modelData.count - 1, section: 0)
    collectionView.insertItems(at: [indexPath])
}

An item with name “John” will be appended to the modellData array and a new Collection View Cell will be displayed at the end of the other cells.

Run Project

Build and Runthe project and select the Add Item Button. Each time a cell with the name of “John” will be added.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK