ios 在 Swift 中以编程方式将 UIScrollView 滚动到子 UIView(子视图)的顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39018017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:57:14  来源:igfitidea点击:

Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

iosswiftuiscrollview

提问by dyson returns

I have a few screens worth of content within my UIScrollView which only scrolls vertically.

我的 UIScrollView 中有几个屏幕的内容,它们只能垂直滚动。

I want to programmatically scroll to a view contained somewhere in it's hierarchy.

我想以编程方式滚动到包含在层次结构中某处的视图。

The UIScrollView move so that the child view is at the top of the UIScrollView (either animated or not)

UIScrollView 移动以便子视图位于 UIScrollView 的顶部(无论是否动画)

回答by dyson returns

Here's an extension I ended up writing.

这是我最终写的一个扩展。

Usage:

用法:

Called from my viewController, self.scrollView is an outlet to the UIScrollView and self.commentsHeader is a view within it, near the bottom:

从我的 viewController 调用,self.scrollView 是 UIScrollView 的出口,self.commentsHeader 是其中的一个视图,靠近底部:

self.scrollView.scrollToView(self.commentsHeader, animated: true)

Code:

代码:

You only need the scrollToViewmethod, but leaving in scrollToBottom/ scrollToTopmethods too as you'll probably need those too, but feel free to delete them.

您只需要scrollToView方法,但也保留scrollToBottom/ scrollToTop方法,因为您可能也需要这些方法,但可以随意删除它们。

extension UIScrollView {

    // Scroll to a specific view so that it's top is at the top our scrollview
    func scrollToView(view:UIView, animated: Bool) {
        if let origin = view.superview {
            // Get the Y position of your child view
            let childStartPoint = origin.convertPoint(view.frame.origin, toView: self)
            // Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview
            self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y,width: 1,height: self.frame.height), animated: animated)
        }
    }

    // Bonus: Scroll to top
    func scrollToTop(animated: Bool) {
        let topOffset = CGPoint(x: 0, y: -contentInset.top)
        setContentOffset(topOffset, animated: animated)
    }

    // Bonus: Scroll to bottom
    func scrollToBottom() {
        let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
        if(bottomOffset.y > 0) {
            setContentOffset(bottomOffset, animated: true)
        }
    }

}

回答by Amr Angry

 scrollView.scrollRectToVisible(CGRect(x: x, y: y, width: 1, height:
1), animated: true)

or

或者

scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)

Another way is

另一种方式是

scrollView.contentOffset = CGPointMake(x,y);

and i do it with animated like this

我用这样的动画来做

[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
scrollView.contentOffset = CGPointMake(x, y); }
completion:NULL];

回答by Max Pevsner

scrollView.setContentOffset(CGPoint, animated: Bool)

Where the point's y coordinate is the y coordinate of the frame of the view you want to show relatively to the scrollView's content view.

其中点的 y 坐标是您要显示的视图框架相对于 scrollView 的内容视图的 y 坐标。

回答by Rahul K Rajan

Here is my answer, this is in swift. This will scroll the pages in scrollview infinitely.

这是我的答案,这是快速的。这将无限滚动滚动视图中的页面。

private func startBannerSlideShow()
{
UIView.animate(withDuration: 6, delay: 0.1, options: .allowUserInteraction, animations: {
    scrollviewOutlt.contentOffset.x = (scrollviewOutlt.contentOffset.x == scrollviewOutlt.bounds.width*2) ? 0 : scrollviewOutlt.contentOffset.x+scrollviewOutlt.bounds.width
}, completion: { (status) in
    self.startBannerSlideShow()
})
}

回答by Vitya Shurapov

For me, the thing was the navigation bar which overlapped the small portion of the scrollView content. So I've made 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.Topand the value(constant field) set to 0
  • 尺寸检查器 - 滚动视图 -内容插入 --> 从自动更改为从不。
  • Size Inspector - Constraints- "Align Top to" (Top Alignment Constraints)- 第二项 -->从 Superview.Top 更改为 Safe Area.Top并将值(常量字段)设置为 0

Content insets - NeverAlign ScrolView.Top to Safe Area.Top

内容插入 - 从不Align ScrolView.Top to Safe Area.Top

回答by Haim

For me scrollRectToVisible()didn't work (see here), so I used setContentOffset()and calculated it myself, based on AMAN77's answer:

对我来说scrollRectToVisible()不起作用(见这里),所以我setContentOffset()自己使用并计算了它,基于 AMAN77 的回答:

extension UIScrollView {

    func scrollToView(view:UIView, animated: Bool) {
        if let superview = view.superview {
            let child = superview.convert(view.frame, to: self)
            let visible = CGRect(origin: contentOffset, size: visibleSize)
            let newOffsetY = child.minY < visible.minY ? child.minY : child.maxY > visible.maxY ? child.maxY - visible.height : nil
            if let y = newOffsetY {
                setContentOffset(CGPoint(x:0, y: y), animated: animated)
            }
        }
    }

}

It is for a horizontal scroll view, but the same idea can be applied vertically too.

它用于水平滚动视图,但同样的想法也可以垂直应用。

回答by Michael Szabo

It is important to point out for any of you beginners out there that you will need to link the UIScrollView from your story board into you code then use the extension ".nameoffunction"

重要的是要指出,对于任何初学者来说,您需要将故事板中的 UIScrollView 链接到您的代码中,然后使用扩展名“.nameoffunction”

For example:

例如:

you import your UIScrollView to your code and name it bob.

您将 UIScrollView 导入您的代码并将其命名为 bob。

you have an extension script written like the one above by "dyson returns"

你有一个类似上面由“dyson Returns”编写的扩展脚本

you now write in your code:

你现在写在你的代码中:

"bob.scrollToTop"

“bob.scrollToTop”

This attached the extension function "scrollToTop" to you UIScrollView in the storyboard.

这将扩展功能“scrollToTop”附加到故事板中的 UIScrollView 。

Good luck and chin up!

祝你好运,振作起来!

回答by YannSteph

For scroll to top or bottom with completion of the animation

用于在动画完成时滚动到顶部或底部

// MARK: - UIScrollView extensions

extension UIScrollView {
    /// Animate scroll to bottom with completion
    ///
    /// - Parameters:
    ///   - duration:   TimeInterval
    ///   - completion: Completion block
    func animateScrollToBottom(withDuration duration:  TimeInterval,
                            completion:             (()->())? = nil) {

        UIView.animate(withDuration: duration, animations: { [weak self] in
            self?.setContentOffset(CGPoint.zero, animated: false)
            }, completion: { finish in
                if finish { completion?() }
        })
    }

    /// Animate scroll to top with completion
    ///
    /// - Parameters:
    ///   - duration:   TimeInterval
    ///   - completion: Completion block
    func animateScrollToBottomTop(withDuration duration:  TimeInterval,
                                  completion:             (()->())? = nil) {
        UIView.animate(withDuration: duration, animations: { [weak self] in
            guard let `self` = self else {
                return
            }
            let desiredOffset = CGPoint(x: 0, y: -self.contentInset.top)
            self.setContentOffset(desiredOffset, animated: false)

            }, completion: { finish in
                if finish { completion?() }
        })
    }
}