下タブ。下タブ押下時の処理も書いた。
以下、ViewControllerをVCとする。
UITabBarController
A container view controller that manages a multiselection interface, where the selection determines which child view controller to display.
開発環境
Xcode: Version 11.6 (11E708)
Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53)
Target: x86_64-apple-darwin19.6.0
実装したもの
ポイント
- 1つ目のタブ押下で TableView を一番上に遷移
- 2つ目のタブ押下で TableView を一番下に遷移
- タブ遷移時には上記の処理を行わない(以前の状態を保つ)
Storyboard全体
Xcode > Editor > Embed in > TabBacController
TableViewの位置変更
タブ押下時の TableView の位置変更の実装。
extension PinkViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// 後述
if tabBarController.selectedIndex != 1 {
return
}
tableView.scrollToRow(at: IndexPath(row: items.count - 1, section: 0), at: .bottom, animated: true)
}
}
タブ押下時の処理でハマったところ
問題
下タブ押下時の処理は UITabBarControllerDelegate
を準拠させたクラスに書く。
そこで、下記の事象にあたった。
- VC1 で VC2 に紐づく下タブ押下
- VC2 で VC1 に紐づく下タブ押下
2.の際に、VC1 遷移時に VC2 で UITabBarControllerDelegate
を準拠させたクラスの処理が実行されてしまう。
解決法
現在のVCとTabBarControllerが保有しているVCで比較してdelegateの切り替えを行おうとしたが、上手くいかなかった。
そこで、selectedIndex を用いて解決した。
extension PinkViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// 1は PinkViewController が TabBarController に登録されている index
if tabBarController.selectedIndex != 1 {
return
}
// 処理
}
}