[Swift] Let's make Pokemon Index using UICollectionView by swift code

7:04:00 AM 4 Comments

Hi guys,

Today I'm going to show you making a UICollectionView in iOS by using Swift. Let's do something a bit more interested so we will create a Pokemon Index in iOS application.

Getting Started

Open Xcode -> New Project and select "Single View Application". Next type in project name "PokemonIndex"


Then download the PokemonImage.zip and extract it somewhere else.

Create a collection view

Do the following steps to create a User Interface of Pokemon Index:
  1. - Open Main.storyboard -> click on the created View Controller.
  2. - Navigate to Editor -> Embed In -> Navigation Controller.
  3. - Drag a Collection View into View Controller and make it fit into the whole view.
  4. - Click on the middle of Navigation bar in View Controller, name it "Pokemon Index"
  5. - Select View Controller again, go the Attributes Inspector, un-click the option "Adjust Scroll View Insets"


Next, adding some constraints to Collection View to make it always stay the same as View Controller size.
  1. - Click on the small square icon at the bottom right of Xcode.
  2. - Un-tick constraint to margins, set 4 constraints to 0 and click on the red line next to each box.


Search for image view and put it into the collection view.
  1. - Resize image view 50x50 for easily fit into a collection view.
  2. - Select image view and add constraints as same as collection view as above.

Coding time

Let's do a few writing tasks, open ViewController.swift and add the following lines. But before doing this, remember to import those line on top of the file.

import UIKit
import SpriteKit

Define enum for any Poke related stuff

// Can define any number related to pokemon
enum PokemonInt: Int {
    case PokemonIndexCount = 151
}

ViewController.swift

class ViewController: UIViewController {
    
    @IBOutlet weak var pokemonCollectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        pokemonCollectionView.delegate = self
        pokemonCollectionView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Conform Collection View protocols 

// MARK: - UICollectionViewDelegateFlowLayout protocol
extension ViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let width = UIScreen.mainScreen().bounds.size.width / 5
        let height = width
        
        return CGSize(width: width, height: height)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0.0
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0.0
    }
}

// MARK: - UICollectionViewDataSource protocol
extension ViewController: UICollectionViewDataSource {
    
    // tell the collection view how many cells to make
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return PokemonInt.PokemonIndexCount.rawValue
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = self.pokemonCollectionView.dequeueReusableCellWithReuseIdentifier("PokemonCell", forIndexPath: indexPath) as! PokemonIndexCell
        let texture = SKTexture(imageNamed: "pokemon_\(indexPath.row + 1)")
        
        cell.pokemonImage.image = UIImage(CGImage: texture.CGImage())
        
        return cell
    }
    
}

Add Pokemon Images collection

Now, you have extracted the downloaded images at the top of this tutorial. 
  1. - We will go to Assets.xcassets in project tree view. 
  2. - Click the "+" button at the bottom and select New Sprite Atlas.
  3. - Right click on created Sprites folder - > Import... 
  4. - Select all the images in extracted images folder.

Connect all components with corresponding classes in Main.storyboard

Now, go to Main.storyboard and fill in the custom classes in Collection View Cell and get the missing connection to the right place of it.

Collection View Cell

Select the cell below the collection view in storyboard and navigate to Identity Inspectors. Change custom class as same as below picture.


Move to the Connection Inspector and drag the pokemonImage to ImageView in Collection View cell.


Change the identifier in Attributes Inspector to PokemonCell


ViewController.Swift

Do the same in View Controller, we need to connect the @IBOutlet declared in swift file to the one in this view.


Then move to Collection View and change its background from black to white color.


Run it 

Hit the button on top to run it and enjoy the Pokemon Index :p.

* You can find another sprites with better resolution and change Mode Scale to Fill to another one, that suit your target devices the best.


In case you missed anything, try to have a look in this source code.

Don't hesitate to point out any mistakes in this tutorial. I'm not a super expert but I will try to fix it as soon as possible. So we can learn from each other :).

Feel free to share it if you find it useful.

Thanks


Unknown

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

4 comments: