Skip to content

Instantly share code, notes, and snippets.

@ngeri
Created January 8, 2020 23:24
Show Gist options
  • Save ngeri/a2d91401985c32b52e0e3dad516824e4 to your computer and use it in GitHub Desktop.
Save ngeri/a2d91401985c32b52e0e3dad516824e4 to your computer and use it in GitHub Desktop.
ActionSheetIfAvailable ViewModifier
//
// ContentView.swift
// StackOverflow
//
// Created by Németh Gergely on 2020. 01. 08..
// Copyright © 2020. Németh Gergely. All rights reserved.
//
import SwiftUI
struct iosBackground: ViewModifier {
#if os(OSX)
func body(content: Content) -> some View {
content
}
#else
func body(content: Content) -> some View {
content.background(Color.blue)
}
#endif
}
struct ActionSheetIfAvailable: ViewModifier {
let isPresented: Binding<Bool>
let actionSheet: () -> ActionSheet
func body(content: Content) -> some View {
#if os(OSX)
return content
#else
return content
.actionSheet(isPresented: isPresented, content: actionSheet)
#endif
}
}
extension View {
func actionSheetIfAvailable(isPresented: Binding<Bool>, content: @escaping () -> ActionSheet) -> some View {
modifier(ActionSheetIfAvailable(isPresented: isPresented, actionSheet: content))
}
}
struct DemoView: View {
@State var showActionSheet = true
var body: some View {
Text("Hello, demo!").padding()
.modifier(iosBackground())
.actionSheetIfAvailable(isPresented: $showActionSheet) {
ActionSheet(
title: Text("Actions"),
message: Text("Available actions"),
buttons: [
.cancel { },
.default(Text("Action")),
.destructive(Text("Delete"))
]
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
DemoView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment