Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift(以编程方式将 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)
推荐答案
这是我最后写的一个扩展.
Here's an extension I ended up writing.
用法:
从我的 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(子视图)的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式将 UIScrollView 滚动到 Swift 中的子 UIV
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01