Get UIScrollView to scroll to the top

前端 未结 15 1863
眼角桃花
眼角桃花 2020-12-07 08:41

How do I make a UIScrollView scroll to the top?

相关标签:
15条回答
  • 2020-12-07 09:28

    iOS 11 and above

    Try to play around with the new adjustedContentInset (It should even work with prefersLargeTitles, safe area etc.)

    For example (scroll to the top):

    var offset = CGPoint(
        x: -scrollView.contentInset.left, 
        y: -scrollView.contentInset.top)
    
    if #available(iOS 11.0, *) {
        offset = CGPoint(
            x: -scrollView.adjustedContentInset.left, 
            y: -scrollView.adjustedContentInset.top)    
    }
    
    scrollView.setContentOffset(offset, animated: true)
    
    0 讨论(0)
  • 2020-12-07 09:28

    Swift 3.0.1 version of rob mayoff's answer :

    self.scrollView.setContentOffset(
    CGPoint(x: 0,y: -self.scrollView.contentInset.top),
    animated: true)
    
    0 讨论(0)
  • 2020-12-07 09:34

    UPDATE FOR iOS 7

    [self.scrollView setContentOffset:
        CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
    

    ORIGINAL

    [self.scrollView setContentOffset:CGPointZero animated:YES];
    

    or if you want to preserve the horizontal scroll position and just reset the vertical position:

    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
        animated:YES];
    
    0 讨论(0)
  • 2020-12-07 09:34

    In SWIFT 5 Just set content Offset to zero

    scrollView.setContentOffset(CGPoint.zero, animated: true)
    
    0 讨论(0)
  • 2020-12-07 09:36

    For Swift 4

    scrollView.setContentOffset(.zero, animated: true)
    
    0 讨论(0)
  • 2020-12-07 09:37

    It's very common when your navigation bar overlaps the small portion of the scrollView content and it looks like content starts not from the top. For fixing it I did 2 things:

    • Size Inspector - Scroll View - Content Insets --> Change from Automatic to Never.
    • Size Inspector - Constraints- "Align Top to" (Top Alignment Constraints)- Second item --> Change from Superview.Top to Safe Area.Top and the value(constant field) set to 0

    0 讨论(0)
提交回复
热议问题