检测 UIScrollView 是否具有滚动高度



我有一个UIScrollView,有时有足够的contentHeight来滚动,有时没有。我还有一个按钮,它基于用户滚动到滚动视图的底部。

如果不用户执行操作,如何检测滚动视图是否具有要滚动的内容高度,以便我可以适当地设置按钮的默认isEnabled

谢谢!

您可以在 UIScrollView 上创建扩展

extension UIScrollView {
  var contentUntilBotttom: CGFloat {
    return max(contentSize.height - frame.size.height - contentOffset.y, 0)
  }
  var isAtTheBottom: Bool {
    return contentUntilBotttom == 0
  }
}

如果您使用的是 RxSwift,您可以观察到以下更改:

extension Reactive where Base == UIScrollView {
  var isAtTheBottom: ControlEvent<Bool> {
    let source = contentOffset
      .map({ _ -> Bool in
        return self.base.isAtTheBottom
      })
    return ControlEvent(events: source)
  }
}
// So then subscribe to it
scrollView.rx.isAtTheBottom
  .subscribe(onNext: { (isAtTheBottom) in
    // Update anithing you need
})

最新更新