Search
Saturday 14 December 2019
  • :
  • :

CollectionView in Swift – Tutorial Alert

One-liner: In this tutorial iOS developers India will make you learn how to use collection view like gallery view. This tutorial is implemented in Xcode 8 and built for iOS 10.

Start with creating one single view application with product name CollectionViewDemo. In the language field select swift language and devices field select universal.

First, we have to add one UICollectionViewCell class file for that go to File   New File iOS Cocoa Touch Class. Name of the class file set CollectionViewCell and subclass select UICollectionViewCell.Please check below screenshot for more info.

1

Now open CollectionViewCell.swift and declare one IBOutlet variable of the image view. Next, implement one method with a string parameter for setting an image into the image view. This is shown in below screenshot.

2

Open Main.storyboard file and drag one collection view from the object library to the main view. Ctrl + Drag from collection view to ViewController.swift and make IBOutlet Connection. Select CollectionView from an outline and go to Attribute Inspector change Flow in Layout and Vertical in Scroll Direction. Check below screenshot.

3

Select CollectionViewCell and set custom class as CollectionViewCell also change cell size to 300 X 300 px. Drag one UIImageView from the object library and add to UICollectionViewCell. Please check below screenshot for more info.

4

Now open ViewController.swift file and declare one NSMutableArray with some picture names. In viewDidLoad() method call reload collection view data.

5

Next methods are UICollectionViewDataSorce. In numberOfItemInSection() method we set total number of array count. In cellForRowAtIndexPath() we declare object of CollectionViewCelland set reusable identifier. Also, call the set image method by passing an image name from array.Check below Screenshot for more info.

6

Next method UICollectionView Delegate, called when the user clicks on any image. In this method, we implement one alert view to show the user selected image number.

7

Next method is UICollectionView Flow Layout. These methods used for setting picture dimension and setting both side inset.

8

For display, images add it into Assets like below screenshot.

9

Now build and run the project. If everything is correct, your app should run properly, and you will see below output. You can see that images are set like a gallery view and also check with a rotating device.

Save

Save



Vijay is a compulsive blogger who likes to educate like-minded people on various new technologies and trends. He works with Aegis SoftTech as a software developer and has been developing software for years. Stay Connected to him on Facebook and Google+.