Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีสร้าง Tab Bar Layout ในแอป iOS

สร้าง Tab Bar Interface บน iOS ด้วย UITabBarController

Tab Bar อยู่ด้านล่างหน้าจอ ใช้สลับระหว่าง Section หลักของแอป (สูงสุด 5 tabs บน iPhone, มากกว่าบน iPad)

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → Single View App → ชื่อ "TabBarController"

ขั้นตอนที่ 2: เพิ่ม Tab Bar Controller ใน Storyboard

  1. ลบ View Controller เดิมออก
  2. Object Library → ค้นหา "Tab Bar Controller" → ลากมา
  3. จะได้: Tab Bar Controller + 2 View Controllers (Item 1, Item 2)

ขั้นตอนที่ 3: สร้าง View Controller Classes

  1. New File → Cocoa Touch Class → Subclass of UIViewController
  2. ชื่อ: FirstViewController, SecondViewController

ขั้นตอนที่ 4: กำหนด Class ให้แต่ละ Tab

  • คลิก Item 1 → Identity Inspector → Class: FirstViewController
  • คลิก Item 2 → Identity Inspector → Class: SecondViewController

ขั้นตอนที่ 5: ปรับแต่ง Tab Bar Items

เลือกแต่ละ Tab Bar Item → Attribute Inspector:

  • Title: ชื่อ Tab (Home, Search, Profile, etc.)
  • Image: ไอคองปกติ (25x25pt @1x, 50x50pt @2x, 75x75pt @3x)
  • Selected Image: ไอคอนเมื่อเลือก (Optional)
  • Badge: ตัวเลข/ข้อความเล็ก (Notification Count)

ขั้นตอนที่ 6: ตั้ง Initial View Controller

คลิก Tab Bar Controller → Attribute Inspector → ติ๊ก Is Initial View Controller

ขั้นตอนที่ 7: Customize Appearance (Optional)

// ใน AppDelegate หรือ TabBarController Subclass
UITabBar.appearance().tintColor = .systemBlue        // Selected Item Color
UITabBar.appearance().unselectedItemTintColor = .gray // Unselected Color
UITabBar.appearance().barTintColor = .systemBackground // Background Color
// iOS 15+ ใช้ UITabBarAppearance

รันโปรเจกต์

จะเห็น Tab Bar ด้านล่าง กดสลับ Tab ได้ 2 หน้า (สีพื้นหลังต่างกันในตัวอย่าง)


Best Practices (Apple HIG)

  • ✅ ใช้สำหรับ Navigation ระดับบนสุด (Top-level) เท่านั้น
  • ✅ 3-5 Tabs (iPhone), มากกว่าได้บน iPad
  • ✅ Icon + Label ชัดเจน, ใช้ SF Symbols
  • ✅ Badge สำหรับ Notification Count เฉพาะ
  • ❌ ไม่ควรซ่อน Tab Bar (ยกเว้น Full-screen Media)
  • ❌ ไม่ควรใช้ Tab Bar สำหรับ Actions (ใช้ Toolbar แทน)

Programmatic Approach (ไม่ใช้ Storyboard)

let tabBarController = UITabBarController()

let firstVC = UINavigationController(rootViewController: FirstViewController())
firstVC.tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: "house"), tag: 0)

let secondVC = UINavigationController(rootViewController: SecondViewController())
secondVC.tabBarItem = UITabBarItem(title: "Search", image: UIImage(systemName: "magnifyingglass"), tag: 1)

tabBarController.viewControllers = [firstVC, secondVC]
window?.rootViewController = tabBarController