Xamarin.iOS使用Storyboard的Unwind Segue實作返回頁面功能
主題: |
Xamarin.iOS使用Storyboard的Unwind Segue實作返回頁面功能 |
文章簡介: |
介紹iOS在Storyboard的Unwind Segue實作返回頁面功能,以取代UIViewController的DismissViewController及UINavigationController的PopToViewController。 |
作者: |
謝俊宇 |
版本/產出日期: |
V1.0/2017.08.14 |
• 1.前言
在iOS開發常常會遇到需要返回好幾個之前頁面時,如果實作返回功能的頁面為被Present出來的,就會需要使用UIViewController的DismissViewController,而該頁面是被Push出來的,就會需要使用UINavigationController的PopToViewController。
但是該頁面被設計成都有可能是被Present或被Push出來的,甚至還需要傳值到返回的目的頁面,這時就是需要花費一些心思及時間去實作這個功能,而現在幸運的是可以使用Unwind Segue讓iOS幫助我們處理掉一些複雜的判斷。
• 2.開始前準備
Xcode
Visual Studio for Mac
• 3.畫面呈現
用一個簡單的三個頁面UIViewController,以Present的方式來做各頁面切換。
• 3.1頁面1:為整個APP起始頁面,也是實作Unwind Segue的最後返回的目的頁面,頁面上方用一個UILabel呈現數字1以利區分頁面,中間UIButton使用一般Segue作法Present Modally為前往下個頁面使用。
• 3.2頁面2:單純增加Present畫面層數,是實作Unwind Segue的返回時,預期會被跳過直接返回頁面1,頁面上方用一個UILabel呈現數字2以利區分頁面,中間UIButton使用一般Segue作法Present Modally為前往最後一個頁面使用。
• 3.3頁面3:為整個APP最後一個頁面,也是實作Unwind Segue的,頁面上方用一個UILabel呈現數字3以利區分頁面,中間UIButton會binding到Unwind Segue為返回第一個頁面使用。
• 4.在UIViewController新增Unwind Segue及在Storyboard做Binding
• 4.1在Visual Studio for Mac選擇要編輯的Storybpard使用Xcode開啟,來新增如章節3.的頁面及前往下一個的一般Segue方法。
• 4.2選擇第一個頁面,並打開Assistant Editor並在ViewController新增一個Unwind Segue Method,方法及畫面步驟如下。
4.3在回到Standard Editor,選擇返回的觸發按鈕,並按著control不放,使用滑鼠左鍵從觸發按鈕拉到返回目的頁面的exit再放開,即可看到在4.2新的Unwind Segue Method Name,最後點擊該Unwind Segue。
4.4該頁面的Document Outline,會出現新增的Unwind Segue,即可編輯該Unwind Segue,目前是新增Identifier為BackToOneFromThree。
4.5做完以上步驟,即可關閉Xcode返回Visual Studio for Mac。
• 5.返回後面後動作
• 5.1打開該UIViewController的designer.cs檔即可看到新增的Unwind Segue Method,並以partial method做呈現。
• 5.2在打開該UIViewController的.cs檔,新增實作的partial method,即可像一般Segue在UIViewController的prepareForSegue,實作各頁面傳值。
• 6.參考資料
• Apple Developer Website UnwindSegue Sample Code: https://developer.apple.com/library/content/samplecode/UnwindSegue/Introduction/Intro.html
• Apple Developer Website API Reference UIStoryboardSegue: https://developer.apple.com/documentation/uikit/uistoryboardsegue
• Apple Developer Website Technical Note TN2298(Using Unwind Segues): https://developer.apple.com/library/content/technotes/tn2298/_index.html