Search
Saturday 24 June 2017
  • :
  • :

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 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 image view. Next implement one method with string parameter for setting image into image view. This is shown in below screenshot.

2Open Main.storyboard file and drag one collection view from object library to main view. Ctrl + Drag from collection view to ViewController.swift and make IBOutlet Connection. Select CollectionView from 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 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 image name from array.Check below Screenshot for more info.

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

7

Next method is UICollectionView Flow Layout. This methods are use 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 project. If everything is correct, your app should run properly and you will see below output. You can see that images are set like gallery view and also check with 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+.