Tusker/Tusker/Views/AlertWithData.swift

46 lines
1.4 KiB
Swift

//
// AlertWithData.swift
// Tusker
//
// Created by Shadowfacts on 11/9/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import SwiftUI
struct AlertWithData<Data, A: View, M: View>: ViewModifier {
let title: LocalizedStringKey
@Binding var data: Data?
let actions: (Data) -> A
let message: (Data) -> M
private var isPresented: Binding<Bool> {
Binding(get: {
data != nil
}, set: { newValue in
guard !newValue else {
fatalError("Cannot set isPresented to true without data")
}
data = nil
})
}
init(title: LocalizedStringKey, data: Binding<Data?>, @ViewBuilder actions: @escaping (Data) -> A, @ViewBuilder message: @escaping (Data) -> M) {
self.title = title
self._data = data
self.actions = actions
self.message = message
}
func body(content: Content) -> some View {
content
.alert(title, isPresented: isPresented, presenting: data, actions: actions, message: message)
}
}
extension View {
func alertWithData<Data, A: View, M: View>(_ title: LocalizedStringKey, data: Binding<Data?>, @ViewBuilder actions: @escaping (Data) -> A, @ViewBuilder message: @escaping (Data) -> M) -> some View {
modifier(AlertWithData(title: title, data: data, actions: actions, message: message))
}
}