萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 視圖控制器核心:UITabBarController、UINavigationController 與自訂切換實作

UITabBarController:平行視圖切換主力

建立與配置


let tabBarController = UITabBarController()

let vc1 = MyViewController()
let vc2 = MyOtherViewController()
// 也可包裝在 UINavigationController
let nav1 = UINavigationController(rootViewController: vc1)

tabBarController.viewControllers = [nav1, vc2]
tabBarController.selectedIndex = 0

window.rootViewController = tabBarController

自訂 Tab Bar Item


// 在各子視圖控制器 init 中設定
init() {
    super.init(nibName: "MyViewController", bundle: nil)
    title = "首頁"
    tabBarItem = UITabBarItem(title: "Home",
                              image: UIImage(named: "home"),
                              selectedImage: UIImage(named: "home_selected"))
}

委託回調


func tabBarController(_ tabBarController: UITabBarController,
                      didSelect viewController: UIViewController) {
    let idx = tabBarController.selectedIndex
    UserDefaults.standard.set(idx, forKey: "selectedTab")
    // 角標提示
    viewController.tabBarItem.badgeValue = "\(80)"
}

UINavigationController:堆疊式導航

核心操作

  • pushViewController(_:animated:):進入下一頁。
  • popViewController(animated:):返回上一頁。
  • popToRootViewController(animated:):返回根頁。
  • setViewControllers(_:animated:):一次性替換整個堆疊。

導覽列自訂


navigationItem.title = "標題"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(done))
// 隱藏導覽列
navigationController?.setNavigationBarHidden(true, animated: true)

自訂視圖控制器切換轉場

1. 轉場協議

  • UIViewControllerTransitioningDelegate:提供動畫控制器、互動控制器、呈現控制器。
  • UIViewControllerAnimatedTransitioning:實作 transitionDuration、animateTransition(using:)。

2. 範例:自訂推入動畫


class CustomPushAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using ctx: UIViewControllerContextTransitioning?) -> TimeInterval { 0.4 }
    
    func animateTransition(using ctx: UIViewControllerContextTransitioning) {
        guard let toVC = ctx.viewController(forKey: .to),
              let fromVC = ctx.viewController(forKey: .from) else { return }
        let container = ctx.containerView
        container.addSubview(toVC.view)
        toVC.view.frame = container.bounds.offsetBy(dx: container.bounds.width, dy: 0)
        UIView.animate(withDuration: 0.4, animations: {
            toVC.view.frame = container.bounds
            fromVC.view.frame = container.bounds.offsetBy(dx: -container.bounds.width * 0.3, dy: 0)
        }) { _ in
            ctx.completeTransition(!ctx.transitionWasCancelled)
        }
    }
}

// 使用
let nav = UINavigationController(rootViewController: vc1)
nav.delegate = self // 實作 UINavigationControllerDelegate 回傳 animator

容器視圖控制器模式

將子控制器加入父控制器:


addChild(childVC)
view.addSubview(childVC.view)
childVC.view.frame = containerBounds
childVC.didMove(toParent: self)

// 移除
childVC.willMove(toParent: nil)
childVC.view.removeFromSuperview()
childVC.removeFromParent()

狀態保存與恢復

  • 實作 encodeRestorableState(with:)、decodeRestorableState(with:)。
  • 設定 restorationIdentifier、restorationClass。
  • AppDelegate 回傳 true 於 application(_:shouldSaveApplicationState:)、application(_:shouldRestoreApplicationState:)。

靈活組合 Tab、Navigation、自訂容器與轉場,構建流暢、符合平台規範的導航架構。

copyright © 萬盛學電腦網 all rights reserved