“`html

簡要

在這篇文章中,我們將深入探討如何在 Swift 中設定 TabBar 和 NavigationBar。這將幫助你建立一個功能齊全的應用程式底層架構,並確保你的 UI 設計符合現代應用的需求。

UINavigationController

在 Swift 中,我們可以在 `viewDidLoad` 方法中進行 NavigationBar 的設定。如果你想讓 NavigationBar 的背景變為透明,請注意,單純使用 `.backgroundColor = .clear` 是無法達成的。

無法讓 NavigationBar 背景透明

UINavigationBar.appearance().backgroundColor = .clear

可以讓 NavigationBar 背景透明

UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

Demo
設定透明背景的 NavigationBar

如果你希望去除下方的分隔線,可以設置 `shadowImage` 來達成。

UINavigationBar.appearance().shadowImage = UIImage()

Demo
去除 NavigationBar 下方的分隔線

UITabBarController

在使用 `UITabBarController` 時,必須先將要使用的 Controller 包裝在 Navigation 中,然後利用 `self.addChild` 方法添加進去。這樣就能同時擁有 TabBar 和 NavigationBar 的功能。

override func viewDidLoad() {
    super.viewDidLoad()
    setUpChildViewControllers()
    setUpTabBar()
}

setUpChildViewControllers

在這個方法中,我們將按照順序添加 Child View Controllers,包括 `controller`、`image`(顯示圖片)、`selectedImage`(按下時顯示圖片)和 `title`(標題)。

func setUpChildViewControllers() {
    addChildViewController(childController: Test1ViewController(), image: "wallet", selectedImage: "wallet", title: "1")
    addChildViewController(childController: Test2ViewController(), image: "wallet", selectedImage: "wallet", title: "2")
}
func addChildViewController(childController: UIViewController, image: String, selectedImage: String, title: String) {
    childController.title = title
    childController.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(red: 176.0/255.0, green: 196.0/255.0, blue: 222.0/255.0, alpha: 1)], for: .selected)
    childController.tabBarItem.image = UIImage(named: image)
    childController.tabBarItem.selectedImage = UIImage(named: selectedImage)
    let navigationController = UINavigationController(rootViewController: childController)
    navigationController.navigationBar.barTintColor = .white
    self.addChild(navigationController)
}

setUpTabBar

這個方法負責設置自定義的 TabBar,所設定的顏色和特效將會生效。

func setUpTabBar() {
    self.setValue(CustomTabBar(), forKey: "tabBar")
}

Demo
完成所有設置後,你的應用將擁有上下的 Bar。
設置完成的 TabBar 和 NavigationBar

Uber Eats 仿製

以下是模仿 Uber Eats 應用的設計。
Uber Eats 應用界面

在這裡,上方的 Bar 背景為白色,且保留下方的底線。下方的四個 icon 和 title 全部隱藏,因為我們使用了截圖來獲取 icon。

原生
原生應用界面
仿製
仿製的應用界面


Q&A(常見問題解答)

1. 如何讓 NavigationBar 背景透明?

你可以使用 `UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)` 來設置透明背景。

2. 為什麼我的 TabBar 不顯示?

請確保你已經正確添加了 Child View Controllers,並且調用了 `setUpTabBar()` 方法。

3. 如何自定義 TabBar 的顏色和樣式?

你可以通過創建一個自定義的 TabBar 類別來設置 TabBar 的顏色和樣式,並在 `setUpTabBar()` 方法中進行設置。
“`

Categorized in: