0

How can it be done ?

I tried everything I could find on stack overflow and nothing worked for me. I would like a solution that will work like Instagram. If you scrolled down tap the TabBarItem to go to the top .( I generally use tableviewControllers and not view controllers if that matters the code)

Any help will be appreciated

In swift 2.2 thank you!

What i tried:

//Using the UiTabBarDelegate
class BarsViewController: UITableViewController,UISearchResultsUpdating,UISearchBarDelegate,UISearchDisplayDelegate,UITabBarControllerDelegate,UITabBarDelegate{

    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
            if(item.tag == 1) {
                //your code for tab item 1
                
            tableView.scrollToTop(true)
            
            }
            else if(item.tag == 2) {
                //your code for tab item 2
            }
            else if(item.tag == 4) {
                //your code for tab item 4
                self.tabBarItem.badgeValue = nil
                
                tableView.scrollToTop(true)        }
        }
    }
    
    extension UITableView {
        func scrollToTop(animated: Bool) {
            setContentOffset(CGPoint.zero, animated: animated)
        }
    }
Community
  • 1
  • 1
Newbie Questions
  • 463
  • 1
  • 11
  • 31

2 Answers2

1

In your button action, call tableView.scrollToRow(IndexPath(row: 0, section:0), at scrollPosition: .top, animated: true)

creeperspeak
  • 5,403
  • 1
  • 17
  • 38
  • i had to fix he line to this : `tableView.scrollToRow(NSIndexPath(row: 0, section:0), at, scrollPosition: .top, animated: true)` and i get an error `use of unresolved identifier 'at'` – Newbie Questions Mar 11 '17 at 18:30
  • Yes, you added an extra comma after "at". My code is in swift 3, so you'll need to change it if you're on an older version. – creeperspeak Mar 11 '17 at 18:38
0

Select your tableView and look at the attributes inspector on the right and make sure scrollsToTop is selected or try self.yourTableView.scrollsToTop = true

If you want to scroll to top on an action create an extension like this,

extension UITableView {
func scrollToTop(animated: Bool) {
    setContentOffset(CGPoint.zero, animated: animated)
 }
}

then in the tabbar or button call the function like this,

tableView.scrollToTop(animated: true)

This is in swift 3 but I received the info from this answer and was written in an earlier version of swift, scroll to top of tableView

Community
  • 1
  • 1
K-2SO
  • 233
  • 1
  • 12