Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Custom UITableViewCell Tutorial – TableView with Images and Text in Swift

July 31, 2017 by Belal Khan 8 Comments

Are you looking for Custom UITableViewCell Tutorial? Then you’ve come at the right place. In this post we will create Custom UITableViewCell to create a TableView with Images and Text in Swift. Todays topic is Custom UITableViewCell Tutorial and here we will fetch JSON data from server and then we will display the data to our Custom UITableView. So lets start.

Contents

  • 1 Custom UITableViewCell Tutorial Video
  • 2 Creating a new Project
  • 3 Adding Dependencies
  • 4 Our Web API
  • 5 The Model Class
  • 6 Adding TableView
    • 6.1 Adding TableView with Prototype Cell
    • 6.2 The Data Source and Delegate
    • 6.3 Designing the Prototype Cell
    • 6.4 Giving a Cell Identifier
    • 6.5 Creating a Class for the Cell
    • 6.6 Connecting Cell UI Components with Class
    • 6.7 Assigning the Class to TableViewCell
  • 7 Fetching Data from Server
  • 8 Displaying Data in TableView
  • 9 Custom UITableViewCell Tutorial Source Code
    • 9.1 Share this:
    • 9.2 Related

Custom UITableViewCell Tutorial Video

  • You can learn from this video on youtube as well. The video covers the same thing we are going to do here.

Creating a new Project

  • The first thing we need is an Xcode Project for this Custom UITableViewCell Tutorial. So here we will create a new Single View Application Project with Xcode. I have created a project named CustomTableView.
  • Once the project is created we will add the required dependencies.

Adding Dependencies

  • As I told you we will fetch the data from web for this I will be using Alamofire. The next thing is loading images from URL for this again I will use AlamofireImage.
  • For this we need to create a Podfile. So create a Podfile inside your project and write the following code.
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'CustomTableView' do
use_frameworks!
pod 'Alamofire', '~> 4.4'
pod 'AlamofireImage', '~> 3.1'
end
  • Now you need to run the command pod install. If you are confused about this step you can check my previous tutorial from the below link where I discussed this step in detail.

Firebase User Registration Tutorial using Swift

Our Web API

  • As I told you that we will fetch data from web. And for this we need a web API. So here is my API that I am going to use.

https://simplifiedcoding.net/demos/marvel/

  • You can use the same API or you can also create your own. The above URL will show the following data.

json data

  • You can see we have a list of heroes here and we have number of attributes for each hero. But for this list I will use only name, team and imageurl.

The Model Class

  • So to store the hero we will create a model class. So create a class named Hero.swift and write the following code.
//
//  Hero.swift
//  CustomTableView
//
//  Created by Belal Khan on 30/07/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

class Hero {
    
    var name: String?
    var team: String?
    var imageUrl: String?
    
    init(name: String?, team: String?, imageUrl: String?) {
        self.name = name
        self.team = team
        self.imageUrl = imageUrl
    }
}

Adding TableView

Adding TableView with Prototype Cell

  • Now first add a TableView to your Main.storyboard. And from the right window make prototype cell to one.

custom uitableview cell

  • Also connect this TableView to your ViewController.swift (Using assistant editor press control and drag).

The Data Source and Delegate

  • Select your table view and press control drag it to the top yellow icon which is in start. And select dataSource and then do it again and select delegate.

custom tableview tutorial

Designing the Prototype Cell

  • Now design your prototype cell as shown in the below image.

custom uitableview tutorial

  • As you can see we have an UIImageView for displaying the image and two labels to display some data. So we will display the superhero image, the his name and his team name.

Giving a Cell Identifier

  • Now select the prototype cell and give it an identifier as shown in the below image.

custom uitableview cell

Creating a Class for the Cell

  • Now we need a Swift class for your Cell. So create a Cocoa Touch Class (Go to File -> New -> File…).

cocoa touch class

  • Create a class named ViewControllerTableViewCell.swift.

Connecting Cell UI Components with Class

  • Now open assistant editor and connect your Cell Items with Swift Code (Press Control and Drag it to Code).
  • Once you will do it you will see the following code to your newly created class.
//
//  ViewControllerTableViewCell.swift
//  CustomTableView
//
//  Created by Belal Khan on 30/07/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

class ViewControllerTableViewCell: UITableViewCell {

    @IBOutlet weak var heroImage: UIImageView!
    @IBOutlet weak var labelName: UILabel!
    @IBOutlet weak var labelTeam: UILabel!
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Assigning the Class to TableViewCell

  • Now we need to assign this class for our TableViewCell. For this just select your prototype cell and write the class name on the right window as shown below.

Custom UITableViewCell Tutorial

Fetching Data from Server

  • Now we need to get the Data from our web API. For this we have Alamofire. It is very simple to fetch data we will use the following code.
        Alamofire.request(URL_GET_DATA).responseJSON { response in
            
         
        
        }

Displaying Data in TableView

  • Here is the last part of our Custom UITAbleView Cell Tutorial. Write the following code inside ViewController.swift.
//
//  ViewController.swift
//  CustomTableView
//
//  Created by Belal Khan on 30/07/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit
import Alamofire
import AlamofireImage


//adding class DataSource and Delegate for our TableView
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    
    //the Web API URL
    let URL_GET_DATA = "https://simplifiedcoding.net/demos/marvel/"
    
    //our table view
    @IBOutlet weak var tableViewHeroes: UITableView!
    
    //a list to store heroes
    var heroes = [Hero]()
    
    //the method returning size of the list
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return heroes.count
    }
    
    
    //the method returning each cell of the list
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
    
        //getting the hero for the specified position
        let hero: Hero
        hero = heroes[indexPath.row]
        
        //displaying values
        cell.labelName.text = hero.name
        cell.labelTeam.text = hero.team
        
        
        //displaying image
        Alamofire.request(hero.imageUrl!).responseImage { response in
            debugPrint(response)
        
            if let image = response.result.value {
                cell.heroImage.image = image
            }
        }
        
        return cell
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
     

        //fetching data from web api
        Alamofire.request(URL_GET_DATA).responseJSON { response in
            
            //getting json
            if let json = response.result.value {
                
                //converting json to NSArray
                let heroesArray : NSArray  = json as! NSArray
                
                //traversing through all elements of the array
                for i in 0..<heroesArray.count{
                    
                    //adding hero values to the hero list
                    self.heroes.append(Hero(
                        name: (heroesArray[i] as AnyObject).value(forKey: "name") as? String,
                        team: (heroesArray[i] as AnyObject).value(forKey: "team") as? String,
                        imageUrl: (heroesArray[i] as AnyObject).value(forKey: "imageurl") as? String
                    ))

                }
                
                //displaying data in tableview
                self.tableViewHeroes.reloadData()
            }
        
        }
        
        
        
        self.tableViewHeroes.reloadData()
        // Do any additional setup after loading the view, typically from a nib.
    }

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


}

  • Thats it now run your application in Simulator.
Custom UITableViewCell Tutorial

Custom UITableViewCell Tutorial

  • Bingo! It is working absolutely fine. If you are facing troubles you can get my source code from below link.

Custom UITableViewCell Tutorial Source Code

[sociallocker] Custom UITableView Cell Tutorial Source Code[/sociallocker]

So thats all for this Custom UITableView Cell Tutorial friends. If you are facing some problems then lets discuss it in the comment section. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: Custom UITAbleView, Custom UITableViewCell Tutorial

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. rizan says

    October 9, 2017 at 1:57 pm

    I got error this error: *** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key daftarAnak.’

    Reply
  2. knut says

    October 16, 2017 at 4:26 pm

    Hi thanks for the Tutorial, would you definitely suggest the use of AlmaofireImage or do you think you can get the same results without using it?

    Reply
  3. Rony says

    October 26, 2017 at 8:35 am

    your tutorial is very good, good example and explanation. please make example for pickerview from json too. it will be great!

    Reply
  4. Dheeraj Bhavsar says

    December 7, 2017 at 2:43 am

    How to get full details of heroes in another view controller on tapping on them using JSON and MySQL?

    Reply
    • Lyle says

      August 14, 2018 at 3:29 am

      Hi Dheeraj, did you find a solution to this? I am looking at doing the same.

      Reply
  5. Dharanikumar says

    February 7, 2018 at 6:22 am

    how to add search bar for this table view .i,m using same code its working fine .i want to know how to add search bar for this tableview.

    Reply
  6. Joe says

    July 9, 2018 at 3:37 am

    I tried to do the Connecting Cell UI Components with Class step but I using drag + control I can’t get the cell to connect to ViewControllerTableViewCell. Using Xcode 9.4.1

    Reply
  7. ANAS G says

    August 14, 2018 at 11:43 pm

    thanks a lot it’s just working fine

    if i want to add link for each photo ? i tried to add button on the images .. but will be one link for all images because of arry 🙂 so what is the solution ?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,380)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,248)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (79,974)
  • Download Full High Sierra Installer to Create Bootable USB (70,273)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,256)
  • How to Format USB on Mac? Formatting External Hard… (61,373)
  • Swift JSON Tutorial – Fetching and Parsing… (59,402)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,697)
  • iOS Registration Form Example using PHP and MySQL (48,915)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,145)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·