TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift UICollectionView Tutorial

Use the UICollectionView and implement a UICollectionViewController class.
UICollectionView. This control displays a collection of items—these can be images, text, or anything else. The user can scroll and select items from the collection.
To get started, please create a new Single View Application in Xcode. Open Main.storyboard. In the bottom right, click on the object library (make sure the circle icon is selected).

Then: Scroll down to Collection View Controller. Click and drag it to the part of the window where the View Controller is listed.

Select it. Please select the Collection View Controller in this list and then look at the right-side panels in Xcode. We will change some options.
Is Initial View. This option is not always necessary, but are using to get the quickest results. We set the Collection View Controller as the Initial View Controller.
Add Swift file. Next please add a new Swift file from the Xcode file menu. We will call our file ExampleCollectionController.swift. The initial contents will need to be added.
ExampleCollectionController file: Swift // // ExampleCollectionController.swift // ExampleTime4 // // .... // import Foundation
Inherit UICollectionViewController. This is confusing. In our new Swift file, please inherit from UICollectionViewController. We then provide 3 override funcs.Func

Here: We specify how our Collection View gets its data. The names of the 3 funcs are important—copy and paste them.

Note: The first two funcs return Ints. These indicate to the Collection View how many elements are in the current section.

Finally: The third func (named collectionView) returns an instance of UICollectionViewCell. It is used to render all cells.

ExampleCollectionController, three funcs: Swift // // ExampleCollectionController.swift // ExampleTime4 // // .... // import UIKit // This class should inherit from UICollectionViewController. class ExampleCollectionController: UICollectionViewController { override func numberOfSectionsInCollectionView( collectionView: UICollectionView) -> Int { // Use 3 for demonstration. return 3 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // Use 3 for demonstration. return 3 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Get reusable cell. // ... Use identifier "Example." let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Example", forIndexPath: indexPath) // Make the cell blue. cell.backgroundColor = UIColor.blueColor() // Return the cell. return cell } }
Some research. Let us check the iOS documentation to see if we are doing things correctly. We are supported to inherit from UICollectionViewController when using collection views.

Warning: The above code implementation is not finished: it returns the Int 3, and does nothing useful.

Quote: You create a custom subclass of UICollectionViewController for each collection view that you want to manage.

UICollectionView Controller: apple.com
Specify class. On the right side of Xcode please find the Custom Class drop-down. We want to link the Collection View Controller to our new class we just added.
Change background. For our demonstration, we want bright colors (nothing muted or sophisticated). Please select an aqua color—this is important, no other color will work.
A warning. When you build the program, Xcode reports some warnings. The first is "Prototype collection view cells must have reuse identifiers."

So: Please locate your Collection View Controller in Xcode again. Find the cell in the list.

Click on cell. We now want to adjust some things of our cell. This is cell prototype—it is something all cells are based on. It will have no custom name.
Reusable identifier. Please look at the third method in "ExampleCollectionController." It specifies the string "Example." This is a reusable identifier.

Tip: We must provide a reusable identifier on a cell. Type "Example" into Xcode to specify this (it can be anything, but must match).

Run iPhone simulator. Please click the right triangle button to run the iPhone simulator. The Collection View (a UICollectionView) will render.

Blue: The blue boxes are the cells. Please see how the UIColor.blueColor() method is called in Swift.

Aqua: The background on the UICollectionView is aqua. It covers the entire screen which is not usually ideal.

Section insets. In Xcode we can add some margins and spacing rules. I added a section inset of 20 to ensure that there is enough space at the top.
String arrays, text. Next let us add a string array to our controller file. We will display data based on the contents of the string array.

Animals: We add a 3-element string array. We use "animals.count" in the collectionView function for the item count.

UILabel: In the third func, we some code to create a UILabel and add it to the contentView with addSubview.

Result: Our UICollectionView now has labels based on the contents of a string array. We have blue and white colors.

ExampleCollectionController, string array: Swift // // ExampleCollectionController.swift // ExampleTime4 // // .... // import UIKit class ExampleCollectionController: UICollectionViewController { // Use a 3-item string array. let animals = ["bird", "dog", "cat"] override func numberOfSectionsInCollectionView( collectionView: UICollectionView) -> Int { // Just 1 section for now. return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // Item count equals string array length. return animals.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Get reusable cell. let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Example", forIndexPath: indexPath) // Make the cell blue. cell.backgroundColor = UIColor.blueColor() // Create a UILabel and index the array based on the indexPath. // ... Size the Label. let label = UILabel() label.text = animals[indexPath.item] label.textColor = UIColor.whiteColor() label.sizeToFit() // Add label to the contentView. cell.contentView.addSubview(label) // Done. return cell } }
String arrays, simulator. Here is the output from the above UICollectionView. We have text in our cells based on the contents of a string array.
Tutorial review. We implemented a CollectionViewController in Swift. We ran the program on the iPhone simulator. We are one step closer to a great iPhone program.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf