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
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.
- 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.
- 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.
Designing the Prototype Cell
- Now design your prototype cell as shown in the below image.
- 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.
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…).
- 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.
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.
- 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 🙂
rizan says
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.’
knut says
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?
Rony says
your tutorial is very good, good example and explanation. please make example for pickerview from json too. it will be great!
Dheeraj Bhavsar says
How to get full details of heroes in another view controller on tapping on them using JSON and MySQL?
Lyle says
Hi Dheeraj, did you find a solution to this? I am looking at doing the same.
Dharanikumar says
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.
Joe says
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
ANAS G says
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 ?