UITableView contentOffSet is not working properly

前端 未结 15 1754
滥情空心
滥情空心 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

    It may be because of the "Adjust Scroll View Insets" attribute on the View Controller. See this: https://stackoverflow.com/a/22022366

    EDIT: Be sure to check the value of 'contentInset' to see what's happening, since this also has an effect on the scroll view. This value is changed after viewWillAppear: when "Adjust Scroll View Insets" is set, which seems to be what others are trying to avoid by using dispatch queues and the like.

    0 讨论(0)
  • 2020-12-14 02:32

    After one hour of tests the only way that works 100% is this one:

    -(void)hideSearchBar
    {
        if([self.tableSearchBar.text length]<=0 && !self.tableSearchBar.isFirstResponder)
        {
            self.tableView.contentOffset = CGPointMake(0, self.tableSearchBar.bounds.size.height);
            self.edgesForExtendedLayout = UIRectEdgeBottom;
        }
    }
    
    -(void)viewDidLayoutSubviews
    {
        [self hideSearchBar];
    }
    

    with this approach you can always hide the search bar if is empty

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题