UIScrollView+ScrollToBottom.swift 938 B

123456789101112131415161718192021222324252627282930
  1. //
  2. // UIScrollView+ScrollToBottom.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/14.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIScrollView {
  10. var isOverflowVertical: Bool {
  11. return self.contentSize.height > self.frame.height && self.frame.height > 0
  12. }
  13. func isReachedBottom(withTolerance tolerance: CGFloat = 0) -> Bool {
  14. guard self.isOverflowVertical else { return false }
  15. let contentOffsetBottom = self.contentOffset.y + self.frame.height
  16. return contentOffsetBottom >= self.contentSize.height - tolerance
  17. }
  18. func scrollToBottom(animated: Bool) {
  19. guard self.isOverflowVertical else { return }
  20. let targetY = self.contentSize.height + self.contentInset.bottom - self.frame.height
  21. let targetOffset = CGPoint(x: 0, y: targetY)
  22. self.setContentOffset(targetOffset, animated: true)
  23. }
  24. }