iOS --- 在NSObject子類的執行代碼中實現UIViewController的跳轉

來源:互聯網
上載者:User

iOS --- 在NSObject子類的執行代碼中實現UIViewController的跳轉

在iOS開發中, 要實現UIViewController之間的跳轉,通過navigationController的pushViewController或者UIViewController自身的presentViewController的方式即可。但要求是從一個UIViewController跳到另外一個UIViewController中。如果要從NSObject子類的執行代碼中做跳轉至UIViewController的操作, 要如何?呢?
首先, 說明下為何會有這樣的需求, 即: UICollectionView -> NSObjectSubclass -> UIViewController:
設定UICollectionView的datasource和delegate為一個NSObject的子類, 用於處理所有跟UICollectionView的datasource和delegate相關的邏輯關係. 那麼在該類的執行代碼中可能有調轉到另一個UIViewController的使用情境. 此時, 不能使用pushViewController, 因self根本就沒有navigationController屬性;也不能使用presentViewController, self不是UIViewController的子類。
解決方式可以考慮一下兩種:

delegate的方式

delegate是iOS中非常常見的方法. 設定UICollectionView的xxxDelegate為該NSObjectSubclass, 實現其中的方法xxxDelegateMethod1, 然後在NSObjectSubclass的執行代碼中調用xxxDelegate的xxxDelegateMethod1方法. 該方法的實現在UICollectionView(包含navigationController屬性)中, 因此在其中可以實現UIViewController之間的正常跳轉.

rootViewController

在NSObjectSubclass的執行代碼中, 先擷取當前的rootViewController, 在做UIViewController之間的跳轉:

UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];[rootViewController presentViewController:filterCourseViewController animated:NO completion:nil];

最終, 要實現UIViewController之間的跳轉, pushViewController或presentViewController的執行代碼所處的類self必須要有navigationController屬性, 或者必須是UIViewController的子類.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.