LoginSignup
3
2

More than 5 years have passed since last update.

[ios]segueを使わずに、Navigationbarを残しつつ、画面遷移する方法

Posted at

下記の画像のように画面遷移をしたいと考えたところ。
遷移先のVCにはNavigationbarがないので、遷移元のNavigationbarを残しつつ、遷移することにする。

スクリーンショット 2017-12-14 18.03.43.png

sample.swift
let vc = storyboard!.instantiateViewController(withIdentifier: "detail") as! GroupDetailViewController
            //遷移先のtabbarを非表示にしている
            vc.hidesBottomBarWhenPushed = true
                        //遷移先に渡す変数を宣言
            vc.groupimage = (groupimage?.image)!
            vc.namelabel = item.name!
            vc.joinnumber = String(item.memberofnumber!)
            vc.amountlabel = String(item.payment!)
            vc.groupid = item.groupid!
                        //このメソッドでNavigationbarを残しつつ、遷移する
            self.navigationController?.pushViewController(vc, animated: true)

ただ、このまんまだと、Navigationcontrollerを通らず遷移することになり、Navigationbarの「戻る」をタップすると、「そんなアクションは設定されていない」と怒られてしまいます。
そこで、遷移先で下記のように実装します。特殊なことはしておらず、Navigationbarにボタンを設定して、タップしたら遷移元に戻るように処理を行います。

sample.swift
override func viewDidLoad() {
        super.viewDidLoad()
let leftButton = UIBarButtonItem(title: "戻る", style: UIBarButtonItemStyle.plain, target: self, action: #selector(GroupDetailViewController.gotoback))
                leftButton.tintColor = UIColor.white
                self.navigationItem.leftBarButtonItem = leftButton
    --中略--
}


@objc func gotoback() {
        if UserDefaults.standard.string(forKey: "tappedgroupname") == nil {
          //遷移元に戻る  
          self.navigationController?.popViewController(animated: true)
        } else {
            --中略--
        }
    }

NavigationControllerを取得して、その上で遷移すればいいんだろうけど、やり方がよくわからず力技で実装しました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2