26.%d Xcode — 客製化一個 ViewController 並加入 Navigation Controller
目錄
⦿ 加入 NavigationController,前置作業
⦿ AppDelegate
加入 NavigationController,前置作業
我們都知道如何在 Storyboard 裡將 VC 嵌入 Navigation Controller,只要 VC embed
in Navigation Controller 即可,但程式碼裡如何加入 Navigation Controllers 呢?待我緩緩道來。
每一個專案在創建時,Xcode 會自動加入 Main.storyboard
,做為初始的 Storyboard,在這個 Storyboard 裡初始的 ViewController(VC),就叫做 ViewController,是打開程式後的第一個主要畫面(Launch Screen 不算的話),但是,身為開發者,我們常常不想用這個 ViewController,通常會用一個自己創建的 Cocoa Touch Class
,比方說它叫做 LoginViewController
,一個功能完整的 APP 總不會不需要登入
吧?
所以,我們希望將初始的 ViewController 刪除,然而,Main.storyboard 常也是我們不想要的,比方說我們想要一個 Login.storyboard
,而一旦刪除 Main.storyboard 就出問題了。
報錯或黑屏的原因是,程式找不到預設的進入點
或沒有初始頁
,此外,若刪除 Main.storyboard,還得一併取消 Main Interface
裡的 Main,如下:
不過在新版的 Xcode 中,TARGETS => Deployment Info 裡沒有 Main Interface 了,如下:
但這還沒完,從 iOS 13 以後,我們還需在 Info.plist 裡,刪除 Application Scene Manifest,如下:
因為這裡的 Storyboard Name 就是 Main。
OK!前置作業完成了,下面進到程式碼。
繼續閱讀|回目錄
AppDelegate
由於 iOS 13 以後,AppDelegate 會將 life cycle 的代理方法轉交給 Scene Delegate,所以如果曾經用舊版的人,專案中可能還留有這兩個方法,我們刪除 / 註解它,如下:
當然,如果你不習慣在 SceneDelegate 中操作,我們可以按照下面步驟:
附上參考網址:
接著,我們就來初始化 Window 了!程式碼如下:
設置一個 Window,該 Window 的 rootVC 為 Navigation Controller,而 Navigation Controller 的 rootVC 可以是任何一個自建的 View Controller。
其實這段程式碼相當於在 Storyboard 中,將 View Controller embed in Navigation Controller,由於我們自行生成了一個 Window(通常手機只會有一個 Window),將 Navigation Controller 跟 View Controller 都在這個 Window 上發展。
我們的首頁就會如實呈現:
ViewController 的程式碼如下:
取消 navigationBar 的半透明(isTranslucent),在膠囊那一行才會呈現白色,否則跟底色一樣是黃色的。
加入了兩個 BarButtonItem,左邊的 Item 是鉛筆,右邊的 Item 是設定;接著在下方也加入一個自訂的 Button,按下時,三個 Button 都有不同的 Action 如下:
@objc func doSomeTh() {
print("Hello World!")
}
@objc func toSetting() {
self.navigationController?.pushViewController(SettingViewController(), animated: true)
}
@objc func toAirticle() {
self.navigationController?.pushViewController(AirticleViewController(), animated: true)
}
左邊的 BarButton 是 print 出 Hello World
,右邊的則是 push 出設定頁
,按下下方的 Button 是進到文章頁
,結果如下:
而設定頁的 RightBarButton 的 Action 是這樣寫的:
@objc func back() {
self.navigationController?.popViewController(animated: true)
}
已經嵌入 Navigation Controller 的 View Controller,在推出(push)下一個頁面後,左上角(即 LeftBarButtonItem)已經有一個回前頁的辦法了,倘若你要自己去 call Navigation Controller 的方法,用的就是 popViewController。
完成了!
這次就分享到這,感謝您的閱讀。
繼續閱讀|回目錄
Reference:
附上 GitHub: