UIViewController 是 UIKit 的中樞,也是 iOS 面試與實務中最容易被問倒的一塊。本文把長達兩百多項的介面依主題重組,並在關鍵處補上實作提醒。
@class UIView; @class UINavigationItem, UIBarButtonItem, UITabBarItem; @class UISearchDisplayController; @class UIPopoverController; @class UIStoryboard, UIStoryboardSegue; @class UIScrollView; @protocol UIViewControllerTransitionCoordinator;
幾個容易混淆的角色:UINavigationItem 放在導航列中,包含 leftBarButtonItem、rightBarButtonItem 與 titleView;UITabBarItem 是分欄控制器底部的切換按鈕;UISearchDisplayController 是為 UITableView 搜尋封裝的輔助類;UIPopoverController 是 iPad 專屬,負責以浮動形式呈現臨時視圖;UIStoryboard 自 iOS 5 起提供以故事板描述界面間業務關係的能力,是目前三種界面組織方式(純代碼、代碼加 xib、Storyboard)之一。
typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {
UIModalTransitionStyleCoverVertical = 0, // 由底部滑入
UIModalTransitionStyleFlipHorizontal, // 水平翻轉
UIModalTransitionStyleCrossDissolve, // 交叉溶解
UIModalTransitionStylePartialCurl // 翻頁
};
typedef NS_ENUM(NSInteger, UIModalPresentationStyle) {
UIModalPresentationFullScreen = 0, // 填滿全屏
UIModalPresentationPageSheet, // 橫屏時由下方開始呈現
UIModalPresentationFormSheet, // 由底部呈現,寬度與螢幕一致
UIModalPresentationCurrentContext, // 沿用父控制器的呈現方式
UIModalPresentationCustom,
UIModalPresentationOverFullScreen,
UIModalPresentationOverCurrentContext,
UIModalPresentationPopover,
UIModalPresentationNone = -1
};
實測提醒:UIModalPresentationNone 在呈現時會拋出例外「The specified modal presentation style doesn't have a corresponding presentation controller.」,不要用於 present 場景。
iOS 8 引入 Size Class 概念後,UIViewController 實作了這組協議的預設行為,自訂時可覆寫以調整佈局:
@protocol UIContentContainer <NSObject>
@property (nonatomic, readonly) CGSize preferredContentSize NS_AVAILABLE_IOS(8_0);
// 期望尺寸變更時回呼
- (void)preferredContentSizeDidChangeForChildContentContainer:
(id <UIContentContainer>)container NS_AVAILABLE_IOS(8_0);
// 當子控制器使用 Auto Layout,而其 systemLayoutSizeFittingSize 改變時回呼
- (void)systemLayoutFittingSizeDidChangeForChildContentContainer:
(id <UIContentContainer>)container NS_AVAILABLE_IOS(8_0);
// 決定要傳給子控制器的尺寸;若與子控制器目前尺寸相同,其子控制器的
// viewWillTransitionToSize: 不會被觸發。預設實作直接回傳 parentSize
- (CGSize)sizeForChildContentContainer:(id <UIContentContainer>)container
withParentContainerSize:(CGSize)parentSize NS_AVAILABLE_IOS(8_0);
// 自身 view 尺寸被父層改變時回呼(例如根控制器隨視窗旋轉)
// 覆寫時務必呼叫 super,否則變更無法向下傳遞
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
NS_AVAILABLE_IOS(8_0);
// traitCollection 即將改變時回呼,早於 traitCollectionDidChange:
- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection
withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
NS_AVAILABLE_IOS(8_0);
@end
NS_CLASS_AVAILABLE_IOS(2_0)
@interface UIViewController : UIResponder <NSCoding, UIAppearanceContainer,
UITraitEnvironment, UIContentContainer>
@end
每個協議都有意義:NSCoding 支援歸檔;UIAppearanceContainer 允許統一客製外觀;UITraitEnvironment 透過 traitCollection 取得 Size Class 以決定佈局;UIContentContainer 則提供容器式的尺寸協商。
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; @property(nonatomic, retain) UIView *view; - (void)loadView; - (void)viewDidLoad; - (BOOL)isViewLoaded NS_AVAILABLE_IOS(3_0); @property(nonatomic, readonly, copy) NSString *nibName; @property(nonatomic, readonly, retain) NSBundle *nibBundle; @property(nonatomic, readonly, retain) UIStoryboard *storyboard NS_AVAILABLE_IOS(5_0);
幾個關鍵約定:initWithNibName: 是指定初始器,子類覆寫時必須呼叫 super;若傳入 nil,系統會嘗試載入與類名同名的 nib;view 的 getter 會在首次被存取時觸發 loadView;loadView 不應被直接呼叫,且只在未使用 xib 時才需要覆寫來以程式建立視圖階層。
- (void)loadView; // 建立 view 階層 - (void)viewDidLoad; // view 已載入,適合做初始化與一次性設定 - (void)viewWillAppear:(BOOL)animated; - (void)viewDidAppear:(BOOL)animated; - (void)viewWillDisappear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated; - (void)viewWillLayoutSubviews NS_AVAILABLE_IOS(5_0); // layoutSubviews 之前 - (void)viewDidLayoutSubviews NS_AVAILABLE_IOS(5_0); // layoutSubviews 之後 - (void)didReceiveMemoryWarning; // 已棄用(iOS 6 起) - (void)viewWillUnload NS_DEPRECATED_IOS(5_0, 6_0); - (void)viewDidUnload NS_DEPRECATED_IOS(3_0, 6_0);
實務分工:viewDidLoad 做一次性初始化;viewWillAppear: 做每次出現都要重設的狀態;viewWillLayoutSubviews/viewDidLayoutSubviews 做與尺寸相關的計算。若需要精確的 frame,放在 viewWillAppear: 或 viewDidLayoutSubviews 中比 viewDidLoad 可靠,因為導航列等 chrome 的實際高度此時才確定。
- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender;
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender;
- (BOOL)canPerformUnwindSegueAction:(SEL)action
fromViewController:(UIViewController *)fromViewController
withSender:(id)sender;
- (UIViewController *)viewControllerForUnwindSegueAction:(SEL)action
fromViewController:(UIViewController *)fromViewController
withSender:(id)sender;
- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController
fromViewController:(UIViewController *)fromViewController
identifier:(NSString *)identifier;
shouldPerformSegueWithIdentifier: 回傳 NO 可取消跳轉,適合用來做條件攔截;prepareForSegue:sender: 則是傳遞資料的標準位置。
- (void)presentViewController:(UIViewController *)viewControllerToPresent
animated:(BOOL)flag completion:(void (^)(void))completion;
- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion;
@property(nonatomic, assign) UIModalTransitionStyle modalTransitionStyle;
@property(nonatomic, assign) UIModalPresentationStyle modalPresentationStyle;
@property(nonatomic, assign) BOOL modalPresentationCapturesStatusBarAppearance;
- (BOOL)disablesAutomaticKeyboardDismissal NS_AVAILABLE_IOS(4_3);
// 已棄用
- (void)presentModalViewController:(UIViewController *)modalViewController
animated:(BOOL)animated NS_DEPRECATED_IOS(2_0, 6_0);
- (void)dismissModalViewControllerAnimated:(BOOL)animated NS_DEPRECATED_IOS(2_0, 6_0);
disablesAutomaticKeyboardDismissal 是個經典坑:在 UIModalPresentationFormSheet 樣式下,系統會讓它回傳 YES,導致 resignFirstResponder 收不起鍵盤。解法是覆寫此方法回傳 NO。若 viewController 被包在 UINavigationController 中,則必須在 UINavigationController 上覆寫才有效。
@property(nonatomic, readonly) UIViewController *parentViewController; @property(nonatomic, readonly) UIViewController *presentedViewController NS_AVAILABLE_IOS(5_0); @property(nonatomic, readonly) UIViewController *presentingViewController NS_AVAILABLE_IOS(5_0); @property(nonatomic, assign) BOOL definesPresentationContext NS_AVAILABLE_IOS(5_0); @property(nonatomic, assign) BOOL providesPresentationContextTransitionStyle NS_AVAILABLE_IOS(5_0); - (BOOL)isBeingPresented; - (BOOL)isBeingDismissed; - (BOOL)isMovingToParentViewController; - (BOOL)isMovingFromParentViewController;
後四個方法可以在 viewWillDisappear: 中判斷自己「為何消失」——是被關閉、被切換,還是被父控制器移除,這在客製容器中是必要的判斷依據。
@property(nonatomic, assign) UIRectEdge edgesForExtendedLayout NS_AVAILABLE_IOS(7_0); // 預設 UIRectEdgeAll @property(nonatomic, assign) BOOL extendedLayoutIncludesOpaqueBars NS_AVAILABLE_IOS(7_0); @property(nonatomic, assign) BOOL automaticallyAdjustsScrollViewInsets NS_AVAILABLE_IOS(7_0); @property (nonatomic) CGSize preferredContentSize NS_AVAILABLE_IOS(7_0); - (UIStatusBarStyle)preferredStatusBarStyle; - (BOOL)prefersStatusBarHidden; - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation; - (void)setNeedsStatusBarAppearanceUpdate;
iOS 7 之後 wantsFullScreenLayout 已被棄用,所有控制器預設都是全螢幕,內容會延伸到導航列下方。若不希望被覆蓋,可調整 edgesForExtendedLayout:
self.extendedLayoutIncludesOpaqueBars = NO; self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
另外,同一頁面若有多個 scrollView(如 tableView),應把 automaticallyAdjustsScrollViewInsets 設為 NO,避免內距被重複計算而錯位。
- (UIViewController *)targetViewControllerForAction:(SEL)action sender:(id)sender; - (void)showViewController:(UIViewController *)vc sender:(id)sender; - (void)showDetailViewController:(UIViewController *)vc sender:(id)sender; + (void)attemptRotationToDeviceOrientation NS_AVAILABLE_IOS(5_0); - (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0); - (NSUInteger)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0); - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0);
attemptRotationToDeviceOrientation 的用法是:當你希望介面方向立即跟上裝置方向時,除了改寫 supportedInterfaceOrientations 的返回值,還必須呼叫此方法。
舊式旋轉回呼(willRotateToInterfaceOrientation:duration:、didRotateFromInterfaceOrientation: 等)自 iOS 8 起全部棄用,統一改用 viewWillTransitionToSize:withTransitionCoordinator:,並在 coordinator 的 animateAlongsideTransition 中加入自訂動畫。
@interface UIViewController (UIContainerViewControllerProtectedMethods)
@property(nonatomic, readonly) NSArray *childViewControllers NS_AVAILABLE_IOS(5_0);
- (void)addChildViewController:(UIViewController *)childController NS_AVAILABLE_IOS(5_0);
- (void)removeFromParentViewController NS_AVAILABLE_IOS(5_0);
- (void)transitionFromViewController:(UIViewController *)fromViewController
toViewController:(UIViewController *)toViewController
duration:(NSTimeInterval)duration
options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion NS_AVAILABLE_IOS(5_0);
- (void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;
- (void)endAppearanceTransition;
- (UIViewController *)childViewControllerForStatusBarStyle NS_AVAILABLE_IOS(7_0);
- (UIViewController *)childViewControllerForStatusBarHidden NS_AVAILABLE_IOS(7_0);
- (void)setOverrideTraitCollection:(UITraitCollection *)collection
forChildViewController:(UIViewController *)childViewController NS_AVAILABLE_IOS(8_0);
- (UITraitCollection *)overrideTraitCollectionForChildViewController:
(UIViewController *)childViewController NS_AVAILABLE_IOS(8_0);
@end
@interface UIViewController (UIContainerViewControllerCallbacks)
- (BOOL)shouldAutomaticallyForwardAppearanceMethods NS_AVAILABLE_IOS(6_0);
- (void)willMoveToParentViewController:(UIViewController *)parent NS_AVAILABLE_IOS(5_0);
- (void)didMoveToParentViewController:(UIViewController *)parent NS_AVAILABLE_IOS(5_0);
@end
容器控制器(如 UINavigationController、UITabBarController)的核心責任是正確轉發外觀回呼。實作自製容器時,標準流程為:呼叫 addChildViewController:,執行轉場把新子控制器的 view 加入視圖階層,完成後呼叫 didMoveToParentViewController:。移除時則反向操作。
另外要注意 UIViewControllerHierarchyInconsistencyException:當子控制器的 view 被加入視圖階層,但沿著父鏈找到的第一個擁有 view controller 的父視圖並非其 parentViewController 時,就會拋出此例外。
@interface UIViewController (UIStateRestoration) <UIStateRestoring> @property (nonatomic, copy) NSString *restorationIdentifier NS_AVAILABLE_IOS(6_0); @property (nonatomic, readwrite, assign) Class<UIViewControllerRestoration> restorationClass; - (void)encodeRestorableStateWithCoder:(NSCoder *)coder NS_AVAILABLE_IOS(6_0); - (void)decodeRestorableStateWithCoder:(NSCoder *)coder NS_AVAILABLE_IOS(6_0); - (void)applicationFinishedRestoringState NS_AVAILABLE_IOS(7_0); @end
@interface UIViewController (UIViewControllerEditing)
@property(nonatomic, getter=isEditing) BOOL editing;
- (void)setEditing:(BOOL)editing animated:(BOOL)animated;
- (UIBarButtonItem *)editButtonItem;
@end
@interface UIViewController (UIConstraintBasedLayoutCoreMethods)
- (void)updateViewConstraints NS_AVAILABLE_IOS(6_0); // 覆寫以更新約束,記得呼叫 super
@end
@interface UIViewController(UIViewControllerTransitioning)
@property (nonatomic, assign) id <UIViewControllerTransitioningDelegate> transitioningDelegate
NS_AVAILABLE_IOS(7_0);
@end
@interface UIViewController (UILayoutSupport)
@property(nonatomic, readonly, retain) id<UILayoutSupport> topLayoutGuide NS_AVAILABLE_IOS(7_0);
@property(nonatomic, readonly, retain) id<UILayoutSupport> bottomLayoutGuide NS_AVAILABLE_IOS(7_0);
@end
@interface UIViewController(NSExtensionAdditions) <NSExtensionRequestHandling>
@property (nonatomic, readonly, retain) NSExtensionContext *extensionContext
NS_AVAILABLE_IOS(8_0);
@end
updateViewConstraints 是 Auto Layout 三步流程(update constraints → layout → display)中唯一建議覆寫的環節;topLayoutGuide 與 bottomLayoutGuide 可作為約束參照,處理導航列與工具列的動態高度;transitioningDelegate 則是 iOS 7 自定義轉場動畫的入口;extensionContext 為 iOS 8 應用擴充提供與宿主 App 溝通的通道。
把這份梳理當成索引使用即可:多數日常需求只會落在生命週期、呈現關閉、容器管理與佈局這四塊,其餘在遇到特定場景時再回查。