問題描述
我的 UIScrollView 中有一些屏幕內(nèi)容,它們只能垂直滾動.
I have a few screens worth of content within my UIScrollView which only scrolls vertically.
我想以編程方式滾動到包含在其層次結(jié)構(gòu)中某處的視圖.
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)
推薦答案
這是我最后寫的一個擴(kuò)展.
Here's an extension I ended up writing.
用法:
從我的 viewController 調(diào)用,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)
}
}
}
這篇關(guān)于以編程方式將 UIScrollView 滾動到 Swift 中的子 UIView(子視圖)的頂部的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!