gpt4 book ai didi

ios - 两个独立的 UIViewControllers 上的 UITabBarControllerDelegate - Swift

转载 作者:行者123 更新时间:2023-11-28 10:13:27 25 4
gpt4 key购买 nike

我有以下代码,我试图在 UIViewcontroller 上实现“滚动到顶部”并在另一个 UIViewController 上实现“滚动到开始”。

第一个 VC 有一个 TableView ,第二个 VC 有一个 Collection View 。

-NearMeViewController-
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
//....
}
extension NearMeViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let tabBarIndex = tabBarController.selectedIndex
if tabBarIndex == 0 {
self.nearMeTable.setContentOffset(CGPoint.zero, animated: true)
}
}
}

-MapSearchViewController-
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
//....
}

extension MapSearchViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let tabBarIndex = tabBarController.selectedIndex
if tabBarIndex == 2 && requests.mapEventData.count > 0 {
self.resultsCollectionView?.scrollToItem(at: IndexPath(row: 0, section: 0),
at: .left,
animated: true)
}
}
}

当然,它们都连接到同一个 UITabBar。问题是,当我打开应用程序并按下 tabBarIndex 0 时,它会滚动到表格 View 的顶部。

然后我更改 VC 并尝试按 tabBarIndex 2,因此它会将我带到 Collection View 的第一项。

然后我回到第一个 VC,当我尝试按下 tabBarIndex 0 时,tableview 没有滚动到顶部(就像我第一次打开应用程序时那样)。

但是第二个带有 Collection View 的 VC 工作正常。

知道为什么会发生这种情况吗?

最佳答案

viewDidLoad 不会在每次 VC 出现时被调用,而只会被调用一次(或者之前被释放时)

vc 0 的代理仅设置一次...然后加载 vc1 并将其设置为代理...但随后不再是 vc0。

要让它工作,请在 viewWillAppear 中设置委托(delegate)。

注意

为此一遍又一遍地更改委托(delegate)是很奇怪的...并且检查索引是脆弱的,最好使用 DonMag 的解决方案。

关于ios - 两个独立的 UIViewControllers 上的 UITabBarControllerDelegate - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com