Last active
March 4, 2025 15:50
-
-
Save ryanlintott/0e59e60cff813babc42ca0e6ac7b3221 to your computer and use it in GitHub Desktop.
A conditional SwiftUI view extension that can be used to optionally apply view modifiers based on OS availability. Learn more about how it works here: https://youtu.be/mgplcrJh0K0?si=YNz0IVSiN-3myb08
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
extension View { | |
/// Applies the given transform or returns the untransformed view. | |
/// | |
/// Useful for availability branching on view modifiers. Do not branch with any properties that may change during runtime as this will cause errors. | |
/// - Parameters: | |
/// - transform: The transform to apply to the source `View`. | |
/// - Returns: The view transformed by the transform. | |
@ViewBuilder | |
func ifAvailable(@ViewBuilder _ transform: (Self) -> (some View)?) -> some View { | |
if let transformed = transform(self) { transformed } else { self } | |
} | |
} | |
struct ExampleView: View { | |
var body: some View { | |
Image(systemName: "heart") | |
.resizable() | |
.scaledToFit() | |
.ifAvailable { | |
/// Only use if #availalbe branching inside to ensure no runtime changes | |
if #available(iOS 17, *) { | |
$0.symbolEffect(.bounce.down, value: value) | |
} | |
/// If this closure returns nil it will return the view unmodified | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've updated the code based on a suggestion from Jessy Catterwaul. (Thanks!)