TabBar 建立多分頁的畫面
有兩種方式可以建立多分頁畫面
第一種:一開始創檔案直接建立Tabbed App
預設會有兩個頁面
第二種:自行建立(一開始是空白頁面 single view)
- 點選目前 View Controller
- 從選單選擇 Embed In 下的 Tab Bar Controller
完成後就會呈現
原本一個畫面的 View Controller (右邊) 就被包在 Tab Bar Controller (左邊)
而且標示第一個畫面的箭頭也改成指向 Tab Bar Controller (左邊)
目前只有一個頁面 我們再來增加一個新頁面吧!
- 到元件裡拉一個新的 View Controller 增加到 storyboard
- 在 Tab Bar Controller 按下右鍵 連接到新建立的 View Controller
因為建立了新頁面 所以同時也要建立新的file 來控制 View Controller 喔~
如何在頁面間轉移資料
建立好多個頁面後,我們接著看頁面間是如何轉移資料的吧。
以下範例是將畫面二的文字輸入框的文字,傳送到畫面一。
傳送的原理為:
兩個畫面都被包在 Tab Bar Controller 裡面,所以就需要透過 往回先找到Tab Bar Controller ,再來找到其他頁面,也就是其他 View Controller。
- self.tabBarController => 先找到 Tab Bar Controller
- self.tabBarController?.viewControllers => Tab Bar Controller 有個屬性為 viewControllers 這是一個陣列,就可以拿到加在 Tab Bar Controller 底下 所有的 viewController !!!
- self.tabBarController?.viewControllers?[0] as? ViewController => 再透過陣列[0]取得第一個畫面 , 以及將他 as 為第一個畫面連接的程式碼檔案 也就是 ViewController
NewViewController 程式碼
@IBOutlet weak var textInput: UITextField!@IBAction func ok(_ sender: UIButton) { if let intputText = textInput.text{ if let first = self.tabBarController?.viewControllers?[0] as? ViewController{ // 這樣就可以拿到 畫面一 也就是 ViewController 中的 myLable
first.myLable.text = intputText
}
}
}
如何跳轉頁面
- self.tabBarController => 先找到 Tab Bar Controller
- self.tabBarController?.selectedIndex = 0 => Tab Bar Controller 有屬性 selectedIndex 為目前所選頁面的編號!!!
@IBOutlet weak var textInput: UITextField!@IBAction func ok(_ sender: UIButton) { if let intputText = textInput.text{ if let first = self.tabBarController?.viewControllers?[0] as? ViewController{// 這樣就可以拿到 畫面一 也就是 ViewController 中的 myLable
first.myLable.text = intputText// 這樣就可以跳轉回畫面一
self.tabBarController?.selectedIndex = 0
}
}
}
詳細可以看github連結: