成果物
・タブで画面切り替え
・タブにバッチがつける。タブを押すたびにバッチに+1される
作成手順
・storyboard上で初期のViewControllerからtabBarControllerに差し替える
(矢印とControllerも差し替え)
・最初は、タブが2つ。もう1つ付け足す。
1)ViewControllerを追加
2)TabBarControllerを”Control”キーを押しながら、新規追加したViewControllerまで引っ張る
3)Relationship Segue のview controllersを選択
4) Relation shipが増えてることを確認
・まず、各画面に対応したControllerクラスを作成する。
以下、1つ目。あとは、同様に作成。切り替え時にわかりやすいように背景色とラベル名だけ変える
import UIKit class View3: UIViewController { var pageLabel : UILabel? override func viewDidLoad() { super.viewDidLoad() pageLabel = UILabel() pageLabel!.frame = CGRect(x:20, y:80, width:self.view.bounds.size.width, height:20) pageLabel!.backgroundColor = UIColor.clear pageLabel!.text = "3" self.view.addSubview(pageLabel!) self.view.backgroundColor = UIColor.green } }
・storyboard上で、作成したクラスとの関連付けも忘れないようにする!
・継承クラスをUITabBarControllerに変更
・タブのタイトルとタグを設定。タグはタブを押下された時の出しわけで必要
// タブのタイトルとタグを設定
con1.tabBarItem.title = “AAAAA”
con1.tabBarItem.tag = 1
タブの配置順と、それを反映させる処理。
let conList : Array
= [con1, con2, con3] self.setViewControllers(conList, animated: false)
タブが押下された時の処理をこの中に記述する
*選択された画面を一番上に表示する。画面のリロードなどは行わないので、行いたい場合は別で処理を記述する必要あり
tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {}
・タブにバッチを付ける部分
con1.tabBarItem.badgeValue = String(con1Cnt)
import UIKit class ViewController: UITabBarController { let con1 = View1() let con2 = View2() let con3 = View3() var con1Cnt : Int = 0 var con2Cnt : Int = 0 var con3Cnt : Int = 0 override func viewDidLoad() { super.viewDidLoad() // タブのタイトルとタグを設定 con1.tabBarItem.title = "AAAAA" con1.tabBarItem.tag = 1 con2.tabBarItem.title = "BBBBB" con2.tabBarItem.tag = 2 con3.tabBarItem.title = "CCCCC" con3.tabBarItem.tag = 3 let conList : Array<UIViewController> = [con1, con2, con3] self.setViewControllers(conList, animated: false) } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { switch item.tag { case 1: con1Cnt += 1 // バッチを指定 con1.tabBarItem.badgeValue = String(con1Cnt) case 2: con2Cnt += 1 // バッチを指定 con2.tabBarItem.badgeValue = String(con2Cnt) case 3: con3Cnt += 1 // バッチを指定 con3.tabBarItem.badgeValue = String(con3Cnt) default: break } } }
サンプル
https://github.com/satoNobu/study_swift/commit/edfbcd385711460c096da82a8cfba91ab3f28741