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
// 在各子視圖控制器 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)"
}
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)
UIViewControllerTransitioningDelegate:提供動畫控制器、互動控制器、呈現控制器。UIViewControllerAnimatedTransitioning:實作 transitionDuration、animateTransition(using:)。
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。true 於 application(_:shouldSaveApplicationState:)、application(_:shouldRestoreApplicationState:)。靈活組合 Tab、Navigation、自訂容器與轉場,構建流暢、符合平台規範的導航架構。