以编程方式将scrollview滚动到其底部

时间:2018-06-13 08:41:34

标签: ios swift xcode

我有一个scrollview,并试图以编程方式滚动到底部..

试过这些:

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

}

从:

Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

  let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
  scrollView.setContentOffset(bottomOffset, animated: true)

从:

UIScrollView scroll to bottom programmatically

但两者都没有做任何事......

怎么做?

3 个答案:

答案 0 :(得分:1)

偏移设置不起作用,因为您尝试在生命周期的早期调用。

您可以尝试更新contentOffsetviewDidLayoutSubviews

上的viewDidAppear
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
 scrollView.setContentOffset(bottomOffset, animated: true)

答案 1 :(得分:1)

这是滚动到滚动视图的任何特定子代,滚动视图的顶部或滚动视图的底部的代码。

只需在您的通用类中添加扩展代码,然后在需要的地方调用即可。

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

}

答案 2 :(得分:0)

使用UIScrollView的这段代码滚动或从底部开始:

let point = CGPoint(x: 0, y: self.view.frame.size.height) 
scrollView.contentOffset = point