2018年3月30日金曜日

TabBarにNavigation

以前StoryBoardを使わずにUITabBarControllerStoryBoardを使わずにUINavigationControllerという記事を書きました。
  • Xcode 8.3.3
  • Swift 3.1
今回はUITabBarControllerにNavigationを追加したいと思います。
もちろんStoryBoardは使いません。
全然関係ないですが、これを実現しようとGoogle先生に聞くとStoryBoardやらSegueやらばかりがHITします😇
あれって使ってる人いるんですね😇

親View

import UIKit

class TabViewController: UITabBarController {
 
 private var _Example1: UINavigationController!
 private var _Example2: UINavigationController!
 private var _Example3: UINavigationController!
 
 override func viewDidLoad() {
  super.viewDidLoad()
  
  self.view.backgroundColor = UIColor.white
  
  _Example1 = UINavigationController(rootViewController: Example1ViewController())
  _Example2 = UINavigationController(rootViewController: Example2ViewController())
  _Example3 = UINavigationController(rootViewController: Example3ViewController())
  
  _Example1.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.featured, tag: 1)
  _Example2.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.featured, tag: 2)
  _Example3.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.featured, tag: 3)
  
  self.setViewControllers([_Example1!, _Example2!, _Example3!], animated: false)
 }
 
 override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
 }
}


子となるView

import UIKit

class Example1ViewController: UIViewController {
 override func viewDidLoad() {
  super.viewDidLoad()
  
  self.navigationItem.title = "Example1"
  
  self.navigationItem.leftBarButtonItem = nil
  
  let btnRight = UIBarButtonItem(title: "Next >", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Example1ViewController.goNext))
  self.navigationItem.rightBarButtonItem = btnRight
 }
 
 override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
 }
 
 @objc func goNext() {
  self.navigationController?.pushViewController(Example1NextViewController(), animated: true)
 }
}


子ViewからNavigationで遷移するView

StoryBoardを使わずにUINavigationControllerという記事ではExample2ViewControllerでした(紛らわしくてすいません🙇)
import UIKit

class Example1NextViewController: UIViewController {
 override func viewDidLoad() {
  super.viewDidLoad()
  
  self.navigationItem.title = "Example1Next"
  
  let btnLeft = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Example1NextViewController.goBack))
  self.navigationItem.leftBarButtonItem = btnLeft
  
  self.navigationItem.rightBarButtonItem = nil
 }
 
 override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
 }
 
 @objc func goBack() {
  self.navigationController?.popViewController(animated: true)
 }
}


Example2, 3についても同じように実装すればタブで切替えながらナビからも操作出来るようになります!
自分のコードから抽出して掲載しているので動かない等あればお気軽にどうぞ!

0 件のコメント:

コメントを投稿