Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Created August 19, 2024 16:54
Show Gist options
  • Save drewolbrich/6d51f27d5624c5382393dd37e2408985 to your computer and use it in GitHub Desktop.
Save drewolbrich/6d51f27d5624c5382393dd37e2408985 to your computer and use it in GitHub Desktop.
A wrapper around onScrollPhaseChange that applies it only on visionOS 2 and is a no-op on visionOS 1
//
// OnScrollPhaseChange_visionOS2.swift
//
// Created by Drew Olbrich on 7/23/24.
// Copyright © 2024 Lunar Skydiving LLC. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import SwiftUI
enum ScrollPhase_visionOS2: Equatable {
case idle
case tracking
case interacting
case decelerating
case animating
var isScrolling: Bool {
return self != .idle
}
}
extension View {
/// A wrapper around `onScrollPhaseChange` that applies it only on visionOS 2 and
/// later, and is a no-op on visionOS 1.
///
/// This is necessary because there doesn't appear to be an easy way to
/// conditionally apply SwiftUI view modifiers or scene modifiers for specific OS
/// versions.
func onScrollPhaseChange_visionOS2(_ action: @escaping (_ oldPhase: ScrollPhase_visionOS2, _ newPhase: ScrollPhase_visionOS2) -> Void) -> some View {
if #available(visionOS 2.0, *) {
func convertPhase(_ scrollPhase: ScrollPhase) -> ScrollPhase_visionOS2 {
switch scrollPhase {
case .idle:
return .idle
case .tracking:
return .tracking
case .interacting:
return .interacting
case .decelerating:
return .decelerating
case .animating:
return .animating
}
}
return self.onScrollPhaseChange { (_ oldPhase: ScrollPhase, _ newPhase: ScrollPhase) -> Void in
return action(convertPhase(oldPhase), convertPhase(newPhase))
}
} else {
return self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment