iOS

⌘K
  1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Table Views (UITableView)

Table Views (UITableView)

What is UITableView?

UITableView is a UI component in iOS that displays a scrollable list of items in a single column. It is widely used for displaying lists, menus, messages, or dynamic data.


1. Key Features of UITableView

✅ Supports static and dynamic data
✅ Provides built-in cell reuse mechanism for performance optimization
✅ Supports multiple sections and rows
✅ Allows custom cell designs
✅ Easily integrates with pull-to-refresh, swipe actions, and animations


2. Adding UITableView in Storyboard

  1. Drag & Drop a UITableView from the Object Library.
  2. Set constraints to position it within the view.
  3. In the Attributes Inspector, set the Prototype Cells to 1 (or more, if needed).
  4. Set the UITableView’s delegate and dataSource to the View Controller.
  5. Implement UITableViewDataSource and UITableViewDelegate methods.

3. Implementing UITableView Programmatically

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let tableView = UITableView()
    let data = ["Apple", "Banana", "Cherry", "Mango", "Orange"]

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }

    func setupTableView() {
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.dataSource = self
        tableView.delegate = self

        view.addSubview(tableView)

        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    // MARK: - UITableView DataSource Methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }
}

This creates a simple table view displaying a list of fruits.


4. Customizing UITableView

4.1 Adding Sections in UITableView

func numberOfSections(in tableView: UITableView) -> Int {
    return 2  // Example: Two sections
}

4.2 Customizing Section Headers

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return section == 0 ? "Fruits" : "Vegetables"
}

4.3 Adding Custom Cell Heights

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60.0  // Custom row height
}

5. Creating a Custom UITableViewCell

5.1 Custom Cell Design

import UIKit

class CustomTableViewCell: UITableViewCell {

    let customLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        customLabel.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(customLabel)

        NSLayoutConstraint.activate([
            customLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            customLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20)
        ])
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

5.2 Registering & Using the Custom Cell

tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell
    cell.customLabel.text = data[indexPath.row]
    return cell
}

This creates a table with a custom-designed cell.


6. Handling Row Selection

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Selected Item: \(data[indexPath.row])")
}

➡️ To deselect a row after selection:

tableView.deselectRow(at: indexPath, animated: true)

7. Adding Swipe Actions to Cells

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, view, completionHandler) in
        print("Deleted: \(self.data[indexPath.row])")
        completionHandler(true)
    }
    return UISwipeActionsConfiguration(actions: [deleteAction])
}

This enables swipe-to-delete functionality.


8. Implementing Pull-to-Refresh

let refreshControl = UIRefreshControl()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.refreshControl = refreshControl
    refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
}

@objc func refreshData() {
    // Refresh Logic Here
    refreshControl.endRefreshing()
}

Pull down to refresh the list dynamically.


9. Animating UITableView Updates

9.1 Adding a New Row with Animation

data.append("New Item")
let indexPath = IndexPath(row: data.count - 1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)

9.2 Deleting a Row with Animation

data.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)

10. Common Issues & Fixes

❌ Issue: TableView Not Displaying Data

Fix: Ensure dataSource is set and reloadData() is called.

❌ Issue: Cells Not Reusing Properly

Fix: Ensure you call dequeueReusableCell(withIdentifier:).

❌ Issue: Swipe Actions Not Working

Fix: Ensure trailingSwipeActionsConfigurationForRowAt is implemented properly.


11. Conclusion

✔️ UITableView is a powerful list component in iOS
✔️ Supports dynamic content, custom cells, and animations
✔️ Easily handles user interactions like selection and swipe actions
✔️ Works well with large datasets using reusable cells

Would you like a UITableView implementation for your project? 🚀