Get UIScrollView to scroll to the top

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

How do I make a UIScrollView scroll to the top?

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

    I tried all the ways. But nothing worked for me. Finally I did like this.

    I added self.view .addSubview(self.scroll) line of code in the viewDidLoad. After started setting up frame for scroll view and added components to scroll view.

    It worked for me.

    Make sure you added self.view .addSubview(self.scroll) line in the beginning. then you can add UI elements.

    0 讨论(0)
  • 2020-12-07 09:16

    Use setContentOffset:animated:

    [scrollView setContentOffset:CGPointZero animated:YES];
    
    0 讨论(0)
  • 2020-12-07 09:21

    I think I have an answer that should be fully compatible with iOS 11 as well as prior versions (for vertical scrolling)

    This takes into account the new adjustedContentInset and also accounts for the additional offset required when prefersLargeTitles is enabled on the navigationBar which appears to require an extra 52px offset on top of whatever the default is

    This was a little tricky because the adjustedContentInset changes depending on the titleBar state (large title vs small title) so I needed to check and see what the titleBar height was and not apply the 52px offset if its already in the large state. Couldn't find any other method to check the state of the navigationBar so if anyone has a better option than seeing if the height is > 44.0 I'd like to hear it

    func scrollToTop(_ scrollView: UIScrollView, animated: Bool = true) {
        if #available(iOS 11.0, *) {
            let expandedBar = (navigationController?.navigationBar.frame.height ?? 64.0 > 44.0)
            let largeTitles = (navigationController?.navigationBar.prefersLargeTitles) ?? false
            let offset: CGFloat = (largeTitles && !expandedBar) ? 52: 0
            scrollView.setContentOffset(CGPoint(x: 0, y: -(scrollView.adjustedContentInset.top + offset)), animated: animated)
        } else {
            scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: animated)
        }
    }
    

    Inspired by Jakub's solution

    0 讨论(0)
  • 2020-12-07 09:23

    iOS 2.0+ Mac Catalyst 13.0+

    You can try: scrollView.scrollsToTop = true

    You can refer it from documentation of developer.apple.com

    0 讨论(0)
  • 2020-12-07 09:24

    In iOS7 I had trouble getting a particular scrollview to go to the top, which worked in iOS6, and used this to set the scrollview to go to the top.

    [self.myScroller scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    
    0 讨论(0)
  • 2020-12-07 09:25

    Here is a Swift extension that makes it easy:

    extension UIScrollView {
        func scrollToTop() {
            let desiredOffset = CGPoint(x: 0, y: -contentInset.top)
            setContentOffset(desiredOffset, animated: true)
       }
    }
    

    Usage:

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