UINavigationController的簡單總結,uisearchcontroller
UINavigationController是IOS開發中常用的用於視圖切換的控制器. 在對象管理上, UINavigationController採用stack的方式來管理各個view的層級, rootViewController在stack的最底層. 同時, 也提供了諸多方法用於進行view之間的切換及管理等.
常見的方法有pushViewController與popViewController等, 需要注意的是UINavigationController對應的segue的屬性要設定為push方式.
看如下代碼:
var window: UIWindow?func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() //RootTableViewController為自己定義的一個管理tableView的controller var root = RootTableViewController() var navCtrl = UINavigationController(rootViewController: root) //指定將該RootTableViewController放在棧底。 self.window!.rootViewController = navCtrl return true}其中, self.window!.rootViewController = navCtrl即指定了當前的rootViewController.
下面, 建立一個WebView並push到UINavigationController的管理檢視中:
//點擊tableView中的一個cell調用的方法 override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){ //indexPath即代表了所點擊的cell那一行 var row=indexPath.row as Int var data=self.dataSource[row] as XHNewsItem //入棧操作, var webView=WebViewController() webView.detailID=data.newsID self.navigationController.pushViewController(webView,animated:true) }上邊代碼執行的效果即為, 點擊tableView中的一個cell, 會新建立一個WebViewController並將其壓入UINavigationController的view棧中.
則UI上呈現出來的就是該WebView的內容. 同時, 導覽列上會自動呈現相應的返回按鈕, 點擊則會完成將該WebView出棧的操作, 進而回退到之前的tableView中.
而回退的操作即會調用popViewController方法.
針對UINavigationController, 也可以採用storyboard的方式添加. 步驟如下:
1, 選中一個viewController, 然後Editor->Embed in>Navigation Controller, 就可以將該viewController設為該UINavigationController的最底層view.
2, 在storyboard中選中tableView中的table view cell, 右鍵連線至要跳轉的視圖WebView. 設定segue的Identifier及push模式. :
3, 然後在didSelectRowAtIndexPath可以通過調用performSegueWithIdentifier()方法來觸發segue的動作, 以完成view的切換操作. 代碼如下:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var data = dataSource[indexPath.row] as NewsItem selectedUrl = data.newsId // method 1: use the storyboard to add the webview self.performSegueWithIdentifier("web", sender: self) }在兩個視圖之間傳遞資料是通過重寫prepareForSegue方法來實現的.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "web" { var vc = segue.destinationViewController as WebViewController vc.newsId = selectedUrl! // 則在webViewController中就可以使用newsId這個變數了 } }
我們會發現, 使用storyboard會非常的方法, 也是最不易出錯的. 但通過代碼方式添加UINavigationController的方法可能在某些特定情境下非常實用的.
大家都可以多試一試.
最後, 需要記住的是 UINavigationController是採用類似stack的push和pop的方式完成view的切換, 調用方法為pushViewController和popViewController.
而UITabBarController是平級view之間的切換, 調用方法為presentViewController和dismissViewController.