danielsaidi / SwiftUIKit

SwiftUIKit is a Swift SDK that adds extra functionality to Swift & SwiftUI.
MIT License
1.4k stars 54 forks source link

Alert is deprecated in current version #19

Open jeemyeong opened 1 year ago

jeemyeong commented 1 year ago

https://developer.apple.com/documentation/swiftui/alert

I just wanted to give you a heads up that the Alert component used in your package is deprecated in the latest version of SwiftUI. I've created a custom alert as a temporary solution, but it would be awesome if you could update the package to support the current SwiftUI version.

Thanks for creating this package - it's been super helpful for my app, and I really appreciate your work. Looking forward to seeing the update!

Cheers!

// CustomAlert.swift
import SwiftUI

public class CustomAlert: ObservableObject {
    let title: Text
    let message: AnyView
    let content: AnyView

    public init(title: Text, message: some View, content: some View) {
        self.title = title
        self.message = AnyView(message)
        self.content = AnyView(content)
    }

    public init(title: Text, message: some View) {
        self.title = title
        self.message = AnyView(message)
        self.content = AnyView(Button("OK") {})
    }
}
// CustomAlertContext.swift
import SwiftUI

public class CustomAlertContext: ObservableObject {

    public init() {}

    @Published public var isActive = false

    @Published public internal(set) var alertObject: CustomAlert? {
        didSet { isActive = alertObject != nil }
    }

    public var isActiveBinding: Binding<Bool> {
        .init(get: { self.isActive },
                set: { self.isActive = $0 }
        )
    }

    public func dismiss() {
        isActive = false
    }

    public func present(_ alert: CustomAlert) {
        self.alertObject = alert
    }
}
// View+CustomAlert.swift
import SwiftUI

public extension View {

    /**
     Present an alert from a certain context. The alert will
     be presented when the context is active.
     */
    func customAlert(context: CustomAlertContext) -> some View {
        alert(context.alertObject?.title ?? Text(""), isPresented: context.isActiveBinding) {
            context.alertObject?.content
        } message: {
            context.alertObject?.message ?? AnyView(Text(""))
        }
    }
}
danielsaidi commented 1 year ago

Hi @jeemyeong

Happy to hear that the library has helped you out! Thank you for notifying me regarding the deprecated API usage - I'll fix that.