gpt4 book ai didi

swift - UITabBarController 始终在 UIViewController 顶部打开页面

转载 作者:搜寻专家 更新时间:2023-11-01 06:56:03 27 4
gpt4 key购买 nike

我最近在我的代码中实现了一种滚动到 UIViewController 顶部的方法,方法是点击 UITabBar 中的图标两次。该代码位于我的 UITabBarController 代码中。它工作得很好,但是我发现不幸的副作用是每次我在我的应用程序上打开一个页面时,它现在位于 UIViewController 的顶部,而不是我上次离开的地方。我确定这段代码某处有错误

   import UIKit

class TabViewController: UITabBarController, UITabBarControllerDelegate {
var pressedCount: Int = 0


override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self


// Do any additional setup after loading the view.
}
@IBAction func unwindToMain(segue: UIStoryboardSegue) {}

override func viewWillAppear(_ animated: Bool) {

super.viewWillAppear(animated)

self.navigationController?.isNavigationBarHidden = true
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
pressedCount += 1
if pressedCount > 1 {
scrollToTop()
} else {
//do something for first press
}
print("Selected item")
}

// UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
print("Selected view controller")
}
func tabBarController(_ TabViewController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let viewControllers = viewControllers else { return false }
if viewController == viewControllers[selectedIndex] {
if let nav = viewController as? UINavigationController {
guard let topController = nav.viewControllers.last else { return true }
if !topController.isScrolledToTop {
topController.scrollToTop()
return false
} else {
nav.popViewController(animated: true)
}
return true
}
}

return true
}
}


extension UIViewController {
func scrollToTop() {
func scrollToTop(view: UIView?) {
guard let view = view else { return }

switch view {
case let scrollView as UIScrollView:
if scrollView.scrollsToTop == true {
scrollView.setContentOffset(CGPoint(x: 0.0, y: -scrollView.contentInset.top), animated: true)
return
}
default:
break
}

for subView in view.subviews {
scrollToTop(view: subView)
}
}

scrollToTop(view: view)
}

var isScrolledToTop: Bool {
if self is UITableViewController {
return (self as! UITableViewController).tableView.contentOffset.y == 0
}
for subView in view.subviews {
if let scrollView = subView as? UIScrollView {
return (scrollView.contentOffset.y == 0)
}
}
return true
}
}

最佳答案

问题是,当您的 ViewController 消失时,它的 pressedCount 属性仍然设置为 2

所以在 viewWillAppear 中添加这一行来重置它:

pressedCount = 0

还修复了 tabBar 中的 if 语句 didSelect 项以在每次用户按下 tabBar 项两次时重置 pressedCount

if pressedCount > 1 {
scrollToTop()
pressedCount = 0
} else {
//do something for first press
}

关于swift - UITabBarController 始终在 UIViewController 顶部打开页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53285375/

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