Skip to main content

Build Carousel Effect in iOS with Swift Kien Pham

This tutorial I’m going to show you how to build Carousel effect it is the most common, you can see it everywhere you can see it on Instagram or App Store which is beautiful UI you can use a lot of in your app many places  that you want to show beautiful text and beautiful image view


First thing first we need to create a new project and select iOS->SingleView Application
Product Name: Tableview – this the name of your project
·      Company Identifier: KienPhamDev It’s actually the domain name written the other way round. if  you have a domain, you can use your own domain name otherwise you may use mine or just fill in
·      Device family: you can choose universal it’s not important
·      Choose swift as Language

And then we are going to the main storyboard, in this tutorial we want to use ViewController so we just need to drag a new Collection View from Object library


Open pin menu want 16 from the left 16 from the right and I want to use 200 for height, we need to add four constrain and make sure that uncheck constrain to margins

In the next stage, we need to create 3 folder Model, View, Controller
inside of View we need to create a new file we’re going to select Cocoa touch class it’s a subclass of UIcollectionview



So let’s call it NewFeedCollectionCell as well as we want to create XIB file make sure that also create XIB file is checked. Inside of NewFeedCell.xib we need to drag  image view from the object library


and open pin menu I want an image to view 0 from the left from right from the top from button

Inside of NewsFeed Cell.swift we need to make an IBOutlet

Let’s go back our story board and we’re going to select CollectionView to let’s change that NewFeedCell.swift

Now if you hit right click  the NewFeedCell and you’re going to see your outlet here so ImageName drag to Image

Inside of Model folder, we need to create a new file we’re going to call it Product.swift and inside of Product.swift we need to create a struct
import Foundation

struct Product {
   private(set) var imageName:String
   
   init(imageName:String) {
       self.imageName = imageName
   }
}

Inside of Service folder we have to create a new file, I’m going to name it DataService.swift
you can name it whatever you want. Inside of  DataService we need to initialize class like this

//
//  DataService.swift
//  CarouselEffect
//
//  Created by Apple on 6/7/19.
//  Copyright © 2019 Apple. All rights reserved.
//

import Foundation

class DataService {
   static let instance = DataService()
   
   let products = [Product(imageName: "food1.jpg"),Product(imageName: "food2.jpg"),Product(imageName: "food3.jpg")]
   public func getProduct() -> [Product]{
       
       return products
   }
}

After that inside of ViewController we need to implement a couple of protocols,UICollectionViewDelegate, and UICollectionViewDataSource we can put a comma after our View Controller, but we should use an extension to inherit from View Controller it makes your code very clean and doesn't messy
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource{


}


And we need the  create IBoutlet for our Collection

   @IBOutlet weak var newFeedCollectionView:UICollectionView?
inside of  override func viewDidLoad(
newFeedCollectionView?.register(
UINib(nibName: "NewFeedCell", bundle: nil), forCellWithReuseIdentifier: "NewFeedCell")
newFeedCollectionView?.dataSource =
self
newFeedCollectionView?.
delegate = self

Inside of extension we need to add two function
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource{
   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
       return DataService.instance.getProduct().count
       
   }
   
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       
       guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId , for: indexPath) as? NewFeedCell  else {return NewFeedCell()}
       
       let product = DataService.instance.getProduct()[indexPath.row]
       
       cell.updateView(product: product)
       
       return cell
       
       
       
       
   }
   
   
   
}


We need to add two function

1 this method must return an integer and tell the collection view how many items to be displayed
2  this method must return object type of UICollectionviewCell

Now we’re going to  hit command R to build your project, we want to make sure that your application doesn't crash, then your application should look like this


As you see that Images are shown in your collection view but It seems like a basic Collection View for the beginner learn how to build Collection View,  so we want to your Collection View show Image different. Now we need to drag UPCarouselFlowLayout.swift file into your project I have prepared for you


Finally, inside of viewDidLoadwe need to layout for your Collection View

override func viewDidLoad() {
       super.viewDidLoad()
       newFeedCollectionView?.register(UINib(nibName: "NewFeedCell", bundle: nil), forCellWithReuseIdentifier: "NewFeedCell")
       newFeedCollectionView?.dataSource = self
       newFeedCollectionView?.delegate = self
       
       let floawLayout = UPCarouselFlowLayout()
       floawLayout.itemSize = CGSize(width: UIScreen.main.bounds.size.width - 60.0, height: (newFeedCollectionView?.frame.size.height)!)
       floawLayout.scrollDirection = .horizontal
       floawLayout.sideItemScale = 0.8
       floawLayout.sideItemAlpha = 1.0
       floawLayout.spacingMode = .fixed(spacing: 5.0)
       newFeedCollectionView?.collectionViewLayout = floawLayout
       // Do any additional setup after loading the view.
   }
When I hit command + R to rerun our project now it just work exactly as we'd expect

I hope it helps you build an amazing app using Carousel, If you have any question, please leave your comment below this tutorial, You can download the final project right here








Comments

Popular posts from this blog

When is viewWillAppear, viewDidAppear, viewDidLoad, viewWillDisappear actually called

A few months ago I decided to apply for a job at a software company, I interviewed for IOS developer position. After a week I got a result they  gave me an offer 400$ per months, salary not too high, not too low for me  I also  struggled with a lot of questions from my interviewer, so today in this article I will share with you my experiment to answer the question from the interviewer  if you are  IOS developer you are familiar with  viewWillAppear , viewDidAppear , viewDidLoad , viewWillDisappear , and viewDidDisappear  let me ask you a question what is the running order of viewDidAppear , viewDidLoad , viewWillDisappear , and viewDidDisappear. This question sounds easy it’s straightforward. Actually, it very hard to answer, because when you make app maybe you don't care about it , No one tells you before you get an interview ,  now we need to create a new project, inside of ViewController.swift  we need to implement some method...

How to update two images using GCD in swift

If you are IOS developer you can run into a problem when your app download a lot of image from URL maybe your app is crashed or you can't interact with the rest of the application, when I interviewed for a job  a few months ago, I also got this question from my interviewer   He assumed that there are 3 images from URL when user click on the update button all of them will be updated at  the same time so let’s do it a demo to know what happens when your application run without multithreading    Inside of my project I need  some element into ViewController,  As you can see we have 2 images and a button to update our image  Inside of ViewController , we need to hook up all of them with  @IBOutlet and @IBAction it should look like this  As you can see when user click on the update button to download two images from URL, you can't interact with the rest of the application you can’t d...