【问题标题】:scrolling a scrollview to its bottom programmatically以编程方式将滚动视图滚动到其底部
【发布时间】:2018-11-22 18:30:18
【问题描述】:

我有一个滚动视图,正在尝试以编程方式滚动到它的底部..

试过这些:

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

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

怎么做?

【问题讨论】:

  • 在主线程中试试
  • 你在哪里调用这个方法?尝试拨打viewDidAppear
  • @karthikeyan 谢谢!
  • @LalKrishna 谢谢!
  • 现在有什么效果了吗?

标签: ios swift xcode


【解决方案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】:

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

您可以尝试在viewDidLayoutSubviewsviewDidAppear 更新contentOffset

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-31
      • 2013-09-16
      • 2016-01-30
      • 2019-05-23
      • 1970-01-01
      • 2011-12-22
      • 2015-07-21
      • 1970-01-01
      相关资源
      最近更新 更多