UITableView - scroll to the top

前端 未结 30 2757
南方客
南方客 2020-11-28 17:22

In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section

相关标签:
30条回答
  • 2020-11-28 18:04

    Swift 4 via extension, handles empty table view:

    extension UITableView {
        func scrollToTop(animated: Bool) {
            self.setContentOffset(CGPoint.zero, animated: animated);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 18:04

    If you i would like move scroll animation in the table, use this code. The scroll move to top with animation in .5 seconds.

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    [_tableContent scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    
    [UIView commitAnimations];
    
    0 讨论(0)
  • 2020-11-28 18:05

    This code let's you scroll a specific section to top

    CGRect cellRect = [tableinstance rectForSection:section];
    CGPoint origin = [tableinstacne convertPoint:cellRect.origin 
                                        fromView:<tableistance>];
    [tableinstance setContentOffset:CGPointMake(0, origin.y)];
    
    0 讨论(0)
  • 2020-11-28 18:08

    Swift :

    if you don't have tableView header :

    tableView.setContentOffset(CGPointMake(0,  UIApplication.sharedApplication().statusBarFrame.height ), animated: true)
    

    if so :

    tableView.setContentOffset(CGPointMake(0, -tableViewheader.frame.height   + UIApplication.sharedApplication().statusBarFrame.height ), animated: true)
    
    0 讨论(0)
  • 2020-11-28 18:08

    Here Is The Code To ScrollTableView To Top Programatically

    Swift:

    self.TableView.setContentOffset(CGPointMake(0, 1), animated:true)
    
    0 讨论(0)
  • 2020-11-28 18:11

    DONT USE

     tableView.setContentOffset(.zero, animated: true)
    

    It can sometimes set the offset improperly. For example, in my case, the cell was actually slightly above the view with safe area insets. Not good.

    INSTEAD USE

     tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    
    0 讨论(0)
提交回复
热议问题