LoginSignup
0
1

More than 1 year has passed since last update.

UITabBarControllerの子要素ViewController同士を戯れさせてみた。[Swift5]

Posted at

はじめに

UITabBarControllerをコードで書いていて、子要素のViewControllerから別のViewControllerにアクセスしたいと思い、少し詰まりました。

試したこと

  1. Chapter1
  2. Chapter2
  3. 参考文献

Chapter1

HogeViewController.swift
guard let viewControllers = self.tabBarController?.viewControllers,
     let sample = viewControllers[1] as? SampleViewController else {
     return
}

これだと二行目の条件分岐が引っかかりました。

Chapter2 Answer

実はUITabBarControllerのViewControllersそれぞれにさらにchildrenというプロパティがありました。

HogeViewController.swift
for vc in viewControllers {
     print("vc \(vc.children)")
}

結果

vc [<プロジェクト名.SampleController: 0x7fad4581d800>]
vc [<プロジェクト名.HogeViewController: 0x7fad47865800>]

ということで

HogeViewController.swift

if let child = viewControllers[1].children.first as? SampleViewController {
       //これでSampleViewControllerの値をいじる。
}

他のViewControllerの値を外からいじるのは良くないのかもしれませんが。

参考文献

なし

終わりに

実務未経験ですが、もがき楽しんでおります。

0
1
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
0
1