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

我想通过编程滚动到它的层次 struct 中包含的某个视图.

UIScrollView将移动,以便子视图位于UIScrollView的顶部(动画或非动画)

推荐答案

这是我最后写的一个扩展.

Usage:

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

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

Code:

您只需要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)
        }
    }

}

Swift相关问答推荐

日期格式yyyyyy—MM—dd hh:mm:ss +0000到dd MMM,以swift格式表示""""

MyApp类型不符合协议App''''

SWIFT异步/等待,多个监听程序

当将新值推送到 NavigationStack 时,SwiftUI 的 navigationDestination 已在堆栈的早期声明

Xcode创建GitHub仓库,但未推送所有文件

自定义碰撞形状出现在错误的位置

如何修改下面的代码,使图像 Select 的顺序与使用快速并发的图像呈现的顺序相匹配?

从一个范围减go 多个范围

URL appendPathComponent(_:) 已弃用?

这是 Int64 Swift Decoding 多余的吗?

将基于MyProtocol的泛型函数的参数更改为使用存在的any MyProtocol或some MyProtocol是否会受到惩罚?

`@available` 属性在 macOS 版本上被错误地限制

让我的函数计算数组 Swift 的平均值

如何为多个类 Swift 进行扩展

Swift - 导入我的 swift 类

如何使用 swift 将 Images.xcassets 中的图像加载到 UIImage 中

使用 Swift 以编程方式自定义 UITableViewCell

Facebook SDK 4.0 IOS Swift 以编程方式注销用户

将 UIImage 剪成圆形

iOS:如何检测用户是否订阅了自动更新订阅