ScrollableDirection for UIScrollView

Updated
Apr 10, 2021 9:57 AM
Created
Apr 10, 2021 9:57 AM
Tags
SwiftUIKit
Keywords
UIScrollView
Date

struct ScrollableDirection: OptionSet {

  static let vertical: Self = .init(rawValue: 1 << 1)
  static let horizontal: Self = .init(rawValue: 1 << 2)

  var rawValue: Int

  init(rawValue: Int) {
    self.rawValue = rawValue
  }

  init(from scrollView: UIScrollView) {

    func canScrollHorizontally(scrollView: UIScrollView) -> Bool {

      let contentInset: UIEdgeInsets

      if #available(iOS 11.0, *) {
        contentInset = scrollView.adjustedContentInset
      } else {
        contentInset = scrollView.contentInset
      }

      return (scrollView.bounds.width - (contentInset.right + contentInset.left) < scrollView.contentSize.width)
    }

    func canScrollVertically(scrollView: UIScrollView) -> Bool {

      let contentInset: UIEdgeInsets

      if #available(iOS 11.0, *) {
        contentInset = scrollView.adjustedContentInset
      } else {
        contentInset = scrollView.contentInset
      }

      return (scrollView.bounds.height - (contentInset.top + contentInset.bottom) < scrollView.contentSize.height)
    }

    let _canScrollHorizontally = canScrollVertically(scrollView: scrollView)
    let _canScrollVertically = canScrollVertically(scrollView: scrollView)

    switch (_canScrollVertically, _canScrollHorizontally) {
    case (true, true):
      self = [.horizontal, .vertical]
    case (false, true):
      self = .horizontal
    case (true, false):
      self = .vertical
    case (false, false):
      self = []
    }

  }
}