chmod
chmod

Reputation: 1253

Mac Catalyst - Adding Click + Drag gesture to UITableView/UIScrollView

I am in the process of enabling Catalyst support for a freelancing project — one of the things that I noticed right away is the differing behaviour of scrolling views on MacOS vs iOS. I expected to be able to click and drag UIScrollViews or UITableViews as I would normally in the iOS Simulator, but I am only able to scroll these views using the mouse's scroll wheel (or two finger gesture on a trackpad).

Is there any way I can mimic the UIPanGestureRecognizer behaviour on iOS for a UIScrollView or UITableView using a Click + Drag gesture on MacOS?

Thank you :)

Upvotes: 7

Views: 1252

Answers (4)

aepryus
aepryus

Reputation: 4825

The following will do the trick:

First a convenience extension:

public extension CGPoint {
    static func - (a: CGPoint, b: CGPoint) -> CGPoint {
        return CGPoint(x: a.x-b.x, y: a.y-b.y)
    }
}

Add a pan gesture to the scroll view:

scrollView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(onPan(_:))))

And finally the selector:

private var s0: CGPoint = .zero
@objc func onPan(_ gesture: UIPanGestureRecognizer) {
    let ds: CGPoint = gesture.translation(in: scrollView)
    switch gesture.state {
        case .began:
            s0 = scrollView.contentOffset
        case .changed:
            scrollView.contentOffset = CGPoint(x: 0, y: max(0, min(scrollView.contentSize.height-scrollView.height, (s0-ds).y)))
        default: break
    }
}

(Full set of CGPoint convenience methods included here: https://github.com/aepryus/Acheron)

Upvotes: 1

Fattie
Fattie

Reputation: 12336

It's worth noting that, as of Monterey, if you use two finger gesture on trackpad, then, it does work exactly as if scrolling on a device - including the bounce.

Upvotes: 0

naituw
naituw

Reputation: 1147

If Private API is acceptable, there is a new one in Mac Catalyst 14.0 does exactly this:

- [UIScrollView _setSupportsPointerDragScrolling:]

Upvotes: 5

polymerchm
polymerchm

Reputation: 228

I noted the same for UICollectionViews. I decided to use scroll buttons and have them set the selection, and offsets. You can do the same with UIGestureRecognizers in each cell and then set the offsets, etc of the parent UITableView or UICollectionView. I've not thought about simple UIScrollViews.

Upvotes: 1

Related Questions