UITableView contentOffSet is not working properly

前端 未结 15 1804
滥情空心
滥情空心 2020-12-14 01:48

In viewWillAppear, I have added UISearchBar as my headerview of UITableView. When view loads, I hides UISearchbar under <

15条回答
  •  半阙折子戏
    2020-12-14 02:32

    If your table will always have at least one row, just scroll to the first row of the table and the search bar will be hidden automatically.

    let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
    

    self.tableView.selectRowAtIndexPath(firstIndexPath, animated: false, scrollPosition: .Top)

    If you put the above code on viewDidLoad, it will throw an error because the tableView hasn't loaded yet, so you have to put it in viewDidAppear because by this point the tableView has already loaded.

    If you put it on viewDidAppear, everytime you open the tableView it will scroll to the top.

    Maybe you don't want this behaviour if the tableView remains open, like when it is a UITabBar View Controller or when you do a segue and then come back. If you just want it to scroll to the top on the initial load, you can create a variable to check if it is an initial load so that it scrolls to the top just once.

    First define a variable called isInitialLoad in the view controller class and set it to "true":

    var isInitialLoad = true
    

    And then check if isInitialLoad is true on viewDidAppear and if it is true, scroll to the top and set the isInitialLoad variable to false:

    if isInitialLoad {
        let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0)
        self.tableView.selectRowAtIndexPath(firstIndexPath, animated: false, scrollPosition: .Top)
        isInitialLoad = false
    }
    

提交回复
热议问题