下面兩段自訂 UIBarButtonItem 的程式碼,在 iOS 7 上完全正常:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}
forState:UIControlStateNormal];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:@{@"UITextAttributeTextColor" : [UIColor darkGrayColor]}
forState:UIControlStateNormal];
但在 iOS 6 上,只要開啟某些系統內建的 view controller(例如預覽 PDF 的 QLPreviewController),就會遇到 _UIRecordArgumentOfInvocationAtIndex 例外而崩潰。
查了 StackOverflow 上類似案例後可以確認,這是 iOS SDK 本身的問題—— Питання出在 UIAppearance 的 iOS 6 實作上。當你在全域設定 appearance 的外觀屬性,而某個系統 view controller 內部又要配置自己的 bar button item 時,這套外觀代理的訊息轉發機制就會拿到型別不符的參數,進而觸發例外。
改用以下寫法即可避開:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:@{UITextAttributeTextColor : [UIColor darkGrayColor]}
forState:UIControlStateNormal];
差別在於 key 的形式:直接寫 UITextAttributeTextColor 這個未加引號的識別符,而不是 @"UITextAttributeTextColor" 字串,也不要用 NSForegroundColorAttributeName。前者走的是舊版的 UIAppearance 訊息路徑,能正確處理型別;後兩者在新版路徑下會引發上述例外。
appearance 或 appearanceWhenContainedIn: 設定的樣式會套用到全 App 所有符合條件的元件,包含系統 framework 內部產生的那些。若某個系統畫面 crash 得莫名其妙,第一步該懷疑的就是這裡。setTitleTextAttributes:forState: 更安全,也更容易除錯。UIKit 屬性 vs 字串 key),兩套並存期間混用是問題的溫床。若專案仍需支援 iOS 6,用 NSFoundationVersionNumber_iOS_7_0 或 __IPHONE_7_0 巨集分別處理兩個版本最保險。這類小插曲偶爾會出現,但把原因搞清楚之後,往往也是對 Cocoa Touch 內部機制理解更深一層的機會。