Latest Web Stories

1

Exploring Smartphone Influence on the Brain: Neurological Perspectives

2

Angular vs. React: Which One Should You Choose?

3

Discover Serenity: Your Guide to Mindfulness Apps

4

Discover how smartphone apps can enhance your mindfulness practice: 5 Senses Exercise with Apps

5

Discover How Smartwatches Measure Blood Pressure: Explained Simply

6

13 Exciting Games Launching in April 2024: From Freedom Planet 2 to TopSpin 2K25!

7

Discover the 5 Amazon Big Spring Deals on Tablets from Samsung, Lenovo

8

Big Savings Alert: Amazfit Smart Watches Now on Sale on Amazon!

9

Amazon's Big Spring Sale: Top 6 Anker Souncore Headphones and Earbuds Deals

10

Affordable VR Adventures: The Best Budget VR Headsets

11

Fly in Peace: Discover the Ultimate Noise-Cancelling Headphones for Flying

12

Bringing AI to Life: NVIDIA's Digital Human Technolgies in Healthcare, Gaming, and More

13

Discover Exciting New Games on NVIDIA GeForce NOW!

14

Steam Spring Sale 2024 is here: Explore the 10 Best FPS Games

15

The Future of iPhones: Apple's Bold Step into AI with DarwinAI

16

Discover the Magic of Sonos Soundbar: Transform Your Home Entertainment Experience!

17

Enhance Your Home Fun: 5 Best Sonos Soundbars to Amp Up Your Entertainment!

18

Pinterest Introduces AI-Powered Body Type Ranges for Inclusive Searches

19

Embrace the Next Wave: 35+ AI Tools for Enhanced Productivity in 2024

20

Xbox Gaming Bonanza: Lots of New Games with Xbox Game Pass!

21

Sony Paves the Way for Gaming Evolution with 'Super-Fungible Tokens' Patent

22

Smart Printing Choices: 10 Key Factors to Consider When Buying an HP Printer or Any Printer

23

Projector Picks: Explore the Best Mini Projectors for Big Screen Fun!

24

JavaScript Essentials: Your Quick Start to Web Coding

25

Gaming Laptop Guide 2024: 10 Crucial Checks Before You Buy + Top 5 Picks for you!

26

Gaming Joy Awaits: Explore the Best PS5 Games of 2024

27

Epic Games Special: Dive into Astro Duel 2 for FREE this week. See What’s Coming Next Week!

28

Fitbit Fitness Tracker Guide 2024: Choose Your Perfect Fit

29

Feel the Beat: Exploring Top Over-Ear Headphones

30

Explore the Web Development Strategies in 2024: A Developers Handbook

31

Explore Must-Play Nintendo Switch Games in 2024!

32

Eclipse Ready: CE and ISO Certified Solar Eclipse Glasses for a Safe Sky Spectacle

33

Disney and Pixar’s Inside Out 2 Introduces New Emotions to Riley's World

34

Discover Waze's cool new features for safer and happier drives!

35

Discover the Top Picks: Best Smartwatches for Your Lifestyle

36

Discover the Best Smartphones Trending Now: Your Easy Guide to the Best Picks!

37

Sound Revolution: Discover the Best Bluetooth Speakers of 2024!

38

Discover the 10 Best Productivity Apps to Supercharge Your Daily Tasks

39

Discover,Install and Enjoy: The Best Chrome Extensions for Developers in 2024

40

Crack the Code: Your Guide to Computer Programming Magic in 2024

41

Boost Your Content Creation: 10 ChatGPT Prompts to Supercharge Content Creation Productivity

42

10 Best Tech Companies in Silicon Valley

43

Top 10 Web Development Interview Questions you can...

44

Learn how to Answer Tell me about Yourself

45

5 Books You Need to Read Right Now

46

25 Practical Ways to Earn Money Online

Translate this page in your preferred language:


How to create a custom tableView cell programmatically in Swift iOS?

Article by: Manish Methani

Last Updated: October 3, 2021 at 2:04pm IST
7 min 10 sec read

Custom Cell means you can create your own cell and customize it in your own way. You can add a button, profile image, etc as per your need. We had covered the basic UITableView cell in the previous tutorial. you can just define the basic default cell for your tableView. But to customize it for user-friendly UI you need to define the custom cell.

Final Output

So Lets Start Creating UITableView with a custom cell.

Open Xcode,

Goto File > New > Project > Single View Application > Enter Project Name (eg :- FirstProjectViewController) and Select Language as Swift > Done.

Now you can see a file on the left navigation Menu of Xcode named, ViewController.swift

We start first with AppDelegate.swift File. Copy and paste this code in the didFinishLaunchingWithOptions method (the very first method you can see in Appdelegate.swift)

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
              
        window = UIWindow(frame: UIScreen.main.bounds)
        let mainController = ViewController() as UIViewController
        let navigationController = UINavigationController(rootViewController: mainController)
        navigationController.navigationBar.isTranslucent = false
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()
        
        return true
    }

AppDelegate is the file that is called first when your App Starts. There are many ViewControllers added to your file. So How our App knows which one to start first? So in the didFinishLaunchingApplications, we told our code to begin with the ViewController file.

UINavigationController is mostly what you see in every App. This is a header with teal color as you see in the Final Output Image. Word itself tells its mean. It Controls all the navigation.

self.window?.rootViewController = navigationController

In this way, you can set Root View Controller. In our case we want ViewController.swift file to be the first one to start.

ViewController.swift file looks like this. You might see an error of CustomContactsTableViewCell we will cover this ...Just go step by step to understand the functionality. :-

import UIKit

private let myArray: NSMutableArray = ["C","Objective-C","Swift"]

var myTableView = UITableView()
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "Programming Languages"
       
        self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 0/255.0, green: 128/255.0, blue: 128/255.0, alpha: 1.0)
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        self.navigationController?.navigationBar.tintColor = UIColor.white
        
        
        
        myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60))
        myTableView.register(CustomContactsTableViewCell.self, forCellReuseIdentifier: "cell")
        myTableView.dataSource = self
        myTableView.delegate = self
        self.view.addSubview(myTableView)
        myTableView.backgroundColor = UIColor.clear
        // myTableView.separatorStyle = UITableViewCellSeparatorStyle.none
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 0 // you should probably return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Num: (indexPath.row)")
        print("Value: (myArray[indexPath.row])")
        
        
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomContactsTableViewCell
        
        cell.backgroundColor = UIColor.clear
        cell.nameLabel.text  =  "(myArray [indexPath.row])"
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 60
    }
    
}

A short description of an Example:

We had given a backgroundColor to NavigationBar, Added a Programming Languages title, and given a White text Color to Title.

Here, viewDidLoad() method is called first. In this method, we initialized a UITableView.

myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60))

Then, we registered a data source and delegate methods of TableView. We have to register these methods to implement its delegate methods.

 myTableView.dataSource = self
myTableView.delegate = self

Then you have to register the forCellReuseIdentifier and give it some name which you use in the cellForRowAtIndexPath method of UITableView.

myTableView.register(CustomContactsTableViewCell.self, forCellReuseIdentifier: "cell")

The last line adds tableViewTutorialsTitle as a subView inside view.

 self.view.addSubview(myTableView)

In numberOfRowsInSection we are going to use the count of elements in our NSMutableArray to tell the tableView how many rows to create:

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
  }
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomContactsTableViewCell
        
        cell.backgroundColor = UIColor.clear
        cell.nameLabel.text  =  "(myArray [indexPath.row])"
        
        return cell
    }
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

This method is used to set the height of a row.

Now create CustomContactsTableViewCell.swift

Open Xcode Goto File > New >File > Coca Touch Class > Next > Enter File Name (CustomContactsTableViewCell) and Select Language as Swift > Done.

Now you can see a file on the left navigation Menu of Xcode named, CustomContactsTableViewCellroller.swift Paste code inside CustomContactsTableViewCell.swift where we designed a UI.

import UIKit

class CustomContactsTableViewCell: UITableViewCell {
    
    var nameLabel = UILabel()
    var button = UIButton()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = UITableViewCellSelectionStyle.none
        let boxView = UIView.init(frame: CGRect(x : 12 , y : 12 , width :UIScreen.main.bounds.size.width - 12*2, height : self.frame.size.height))
        self.contentView.backgroundColor = UIColor.clear
        boxView.backgroundColor = UIColor.white
        self.contentView.addSubview(boxView)
        boxView.layer.cornerRadius = 2.0;
        
        
        nameLabel = UILabel(frame:CGRect(x:12 , y:0 , width: boxView.frame.size.width , height: 40) )
        boxView.addSubview(nameLabel)
        nameLabel.textColor = UIColor.black
        
        
        button = UIButton(frame:CGRect(x:boxView.frame.size.width - 90 , y:6 , width: 80 , height: 32) )
        boxView.addSubview(button)
        button.setTitle("Call", for: UIControlState.normal)
        button.titleLabel?.textColor = UIColor.white
        button.backgroundColor = UIColor.init(red: 0/255.0, green: 152/255.0, blue: 152/255.0, alpha: 1.0)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: 1.0)
        button.layer.cornerRadius = 2.0
        button.addTarget(self, action: #selector(self.callButtonClicked), for: UIControlEvents.touchUpInside)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    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
    }
    
    func callButtonClicked()  {
        print("Call Button Clicked")
    }
    
}

In this custom cell, we created boxView which contains a name label and one call button. In this way, you create any custom cell as per your need.

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App