以编程方式将UIScrollView滚动到Swift中的子UIView(子视图)的顶部 [英] Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

查看:293
本文介绍了以编程方式将UIScrollView滚动到Swift中的子UIView(子视图)的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

UIScrollView移动,以便子视图位于UIScrollView的顶部(动画与否)

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

推荐答案

这是我最后写的扩展。

用法:

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

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

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

代码:

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

You only need the scrollToView method, but leaving in scrollToBottom / scrollToTop methods too as you'll probably need those too, but feel free to delete them.

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)
        }
    }

}

这篇关于以编程方式将UIScrollView滚动到Swift中的子UIView(子视图)的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆