Skip to content

Instantly share code, notes, and snippets.

@hammadzz
Created January 12, 2017 03:51
Show Gist options
  • Save hammadzz/4bd2d9d7b15f4e3319d3ed592f715900 to your computer and use it in GitHub Desktop.
Save hammadzz/4bd2d9d7b15f4e3319d3ed592f715900 to your computer and use it in GitHub Desktop.
TabBar Pressing Button Brings it Back to Top of ScrollView
class tapBarController: UITabBarController, UITabBarControllerDelegate {
/// Determines whether the scrolling capability's enabled.
var scrollEnabled: Bool = true
private var previousIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
/*
Always call "super" if you're overriding this method in your subclass.
*/
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
guard scrollEnabled else {
return
}
guard let index = viewControllers?.indexOf(viewController) else {
return
}
if index == previousIndex {
var scrollViews = [UIScrollView]()
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { [weak self] () in
self?.iterateThroughSubviews(self?.view) { (scrollView) in
scrollViews.append(scrollView)
}
guard let scrollView = scrollViews.first else {
return
}
dispatch_async(dispatch_get_main_queue(), {
scrollView.setContentOffset(CGPointZero, animated: true)
})
})
}
previousIndex = index
}
/*
Iterates through the view hierarchy in an attempt to locate a UIScrollView with "scrollsToTop" enabled.
Since the functionality relies on "scrollsToTop", it plugs easily into existing architectures - you can
control the behaviour by modifying "scrollsToTop" on your UIScrollViews.
*/
private func iterateThroughSubviews(parentView: UIView?, onRecognition: (UIScrollView) -> Void) {
guard let view = parentView else {
return
}
for subview in view.subviews {
if let scrollView = subview as? UIScrollView where scrollView.scrollsToTop == true {
onRecognition(scrollView)
}
iterateThroughSubviews(subview, onRecognition: onRecognition)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment