UIScrollView max和min contentOffsets?

Sen*_*ful 5 uiscrollview ios

给定一个配置了任何标准属性的UIScrollView(例如contentInset),我如何获得最小和最大contentOffset?

即当用户一直向左滚动时,contentOffset将被报告为什么?

即如果用户一直向下滚动到右下角,那么contentOffset将被报告为什么?

Sen*_*ful 16

想象一下,我们有以下UIScrollView:

  • contentSize: 500 x 500
  • 框架/边界大小: 200 x 200
  • contentInsets: (10, 10, 20, 20)

计算的contentOffsets:

  • 最小内容偏移:
    • .x:( - -contentInset.left10)
    • .y:( - -contentInset.top10)
  • Max contentOffset
    • .x:contentSize.width - bounds.width + contentInset.right(320)
    • .y:contentSize.height - bounds.height + contentInset.bottom(320)

通常,UIScrollView从contentOffset = (0, 0).但是,当您添加contentInsets时,它会以数量开始偏移.当您将第一个位置滚动到视图中以便您没有看到contentInset时,您将进入contentOffset = (0,0).

类似的事情发生在最后,而不是300是最大偏移,320变成最大.

func minContentOffset(scrollView: UIScrollView) -> CGPoint {
    return CGPoint(
        x: -scrollView.contentInset.left,
        y: -scrollView.contentInset.top)
}

func maxContentOffset(scrollView: UIScrollView) -> CGPoint {
    return CGPoint(
        x: scrollView.contentSize.width - scrollView.bounds.width + scrollView.contentInset.right,
        y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom)
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建一个函数,使用这两个函数来确定滚动视图是否可滚动:

func canVerticallyScroll(scrollView: UIScrollView) -> Bool {
    let scrollableHeight = maxContentOffset(scrollView: scrollView).y
        - minContentOffset(scrollView: scrollView).y
    let viewableHeight = scrollView.bounds.height
    return viewableHeight < scrollableHeight
}
Run Code Online (Sandbox Code Playgroud)

或作为扩展:

extension UIScrollView {

  var minContentOffset: CGPoint {
    return CGPoint(
      x: -contentInset.left,
      y: -contentInset.top)
  }

  var maxContentOffset: CGPoint {
    return CGPoint(
      x: contentSize.width - bounds.width + contentInset.right,
      y: contentSize.height - bounds.height + contentInset.bottom)
  }

  func scrollToMinContentOffset(animated: Bool) {
    setContentOffset(minContentOffset, animated: animated)
  }

  func scrollToMaxContentOffset(animated: Bool) {
    setContentOffset(maxContentOffset, animated: animated)
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我将用“adjustedContentInset”替换“contentInset”。 (2认同)