我有一个滚动视图,并试图以编程方式滚动到其底部。
尝试了这些:
extension UIScrollView {
// 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 中以编程方式将 UIScrollView 滚动到子 UIView (子视图( 的顶部
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
scrollView.setContentOffset(bottomOffset, animated: true)
从:
UIScrollView 以编程方式滚动到底部
但两人都什么也没做...
怎么办?
这是滚动到滚动视图的任何特定子级、滚动视图顶部或滚动视图底部的代码。
只需将扩展代码添加到公共类中,然后从需要的地方调用它。
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)
}
}
}
偏移量设置不起作用,因为您在生命周期的早期尝试调用。
您可以尝试在viewDidLayoutSubviews
或viewDidAppear
更新contentOffset
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
scrollView.setContentOffset(bottomOffset, animated: true)
使用 UIScrollView 的这段代码滚动或从底部开始:
let point = CGPoint(x: 0, y: self.view.frame.size.height)
scrollView.contentOffset = point
将此代码作为扩展添加到 scrollView
func scrollToBottom(animated: Bool = true) {
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
self.setContentOffset(bottomOffset, animated: true)
}