Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tạo Tab Bar Layout trong ứng dụng iOS

Giới thiệu

Tab Bar** xuất hiện dưới cùng màn hình, cho phép chuyển nhanh giữa các chức năng chính của app. Theo Human Interface Guidelines của Apple: trong suốt, có thể có background tint, chiều cao cố định, ẩn khi bàn phím hiện.

Cách tạo Tab Bar Layout trong ứng dụng iOS

Các bước tạo Tab Bar Controller từ Storyboard

Bước 1: Tạo dự án

Xcode → New Project → Single View Application → Tên "TabBarController".

Bước 2: Thêm Tab Bar Controller

Mở Main.storyboard → Object Library → Kéo **Tab Bar Controller** vào canvas.

Cách tạo Tab Bar Layout trong ứng dụng iOS

Bước 3: Xóa View Controller mặc định & tạo ViewController thứ 2

  • Xóa ViewController gốc (mặc định).
  • File → New → File → Cocoa Touch Class → Tên SecondViewController, subclass UIViewController.

Bước 4: Gán Class cho 2 Tab

Chọn Item 1 (Tab 1) → Identity Inspector → Class: ViewController.
Chọn Item 2 (Tab 2) → Identity Inspector → Class: SecondViewController.

Cách tạo Tab Bar Layout trong ứng dụng iOS Cách tạo Tab Bar Layout trong ứng dụng iOS

Bước 5: Tùy chỉnh giao diện

  • Đổi background color: Tab 1 = Xám, Tab 2 = Đen.
  • Đặt icon, title cho mỗi tab trong Tab Bar Item (Attributes Inspector).

Bước 6: Đặt Tab Bar Controller là Initial View Controller

Chọn Tab Bar Controller → Attributes Inspector → Tick **Is Initial View Controller**.

Bước 7: Chạy thử

App chạy với 2 tab chuyển đổi mượt mà:

Cách tạo Tab Bar Layout trong ứng dụng iOS Cách tạo Tab Bar Layout trong ứng dụng iOS

Tạo Tab Bar bằng Code (Programmatically)

// Trong AppDelegate hoặc SceneDelegate
let tabBarController = UITabBarController()

let vc1 = ViewController()
vc1.tabBarItem = UITabBarItem(title: "Trang chủ", image: UIImage(systemName: "house"), tag: 0)

let vc2 = SecondViewController()
vc2.tabBarItem = UITabBarItem(title: "Cài đặt", image: UIImage(systemName: "gear"), tag: 1)

tabBarController.viewControllers = [vc1, vc2]
window?.rootViewController = tabBarController

Lưu ý

  • Tối đa 5 tab hiển thị cùng lúc (iPhone), tab thứ 5 trở đi vào menu "More".
  • Tab Bar height: 49pt (compact), 83pt (regular - iPad/landscape).
  • Sử dụng UITabBarAppearance (iOS 13+) để tùy chỉnh giao diện hiện đại.