← Back to Tutorials

5. UI Elements

Core Concepts

UILabel

Displays read-only text:

let label = UILabel()
label.text = "Welcome to iOS"
label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
label.textColor = .darkText
label.textAlignment = .center

UIButton

Responds to user taps:

let button = UIButton(type: .system)
button.setTitle("Tap Me", for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
// SwiftUI equivalent:
Button("Tap Me") { /* action */ }

UITextField

Accepts user text input:

// UIKit
let textField = UITextField()
textField.placeholder = "Enter your name"
textField.borderStyle = .roundedRect
textField.delegate = self

// SwiftUI
@State private var name = ""
TextField("Enter your name", text: $name)

UITableView

Displays a scrollable list of items. Must implement UITableViewDataSource and UITableViewDelegate:

class MyTableVC: UITableViewController {
    let items = ["Apple", "Banana", "Cherry"]
    
    override func tableView(_ tableView: UITableView,
        numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    override func tableView(_ tableView: UITableView,
        cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
}

UICollectionView

Displays items in a grid layout using UICollectionViewFlowLayout:

let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumInteritemSpacing = 10
let collectionView = UICollectionView(frame: .zero,
    collectionViewLayout: layout)

Navigation Controller

UINavigationController manages a stack of view controllers:

let navController = UINavigationController(
    rootViewController: HomeViewController())
// Push a new screen
navigationController?.pushViewController(
    DetailViewController(), animated: true)
Practice Task: Create a "To Do List" app with a UITextField for adding items, a UITableView to display them, and swipe-to-delete functionality. Add a UINavigationController with a "Edit" button in the navigation bar.