SwiftUI: как выполнить закрытие при закрытии предупреждения?

Я пробовал использовать swiftUI и просмотрел этот учебник Рэя Вендерлиха ... Я заметил, что они не повторно реализовали функциональность "nextRound" ... поэтому я попытался сделать это сам. Возникла проблема (что, возможно, и они сделали):

Основной вопрос более общий:

Используя swiftUI, как вы запускаете функцию, когда предупреждение закрывается - когда пользователь нажимает "ОК". ?

Я пробовал использовать аргумент dismissButton конструктора Alert ...

(а также метод .onDisappear View, но я не могу понять, как применить его к представлению Alert.)

Код:

import SwiftUI

struct ContentView: View {

    @State var shouldShowAlert: Bool = false

    // this never gets called
    func onAlertDismissed() {
        print("you will not see this in the console")
    }

    // this doesn't seem to work
    var dismissButton: some View {

        Button(action: {
            self.onAlertDismissed()
        }) {
            // Bilbo Baggins does not appear -- "OK" still shows
            Text("BILBO BAGGINS")
        }
    }

    var body: some View {

        VStack {
            Spacer()

            Button(action: {
                self.shouldShowAlert = true
            }) {
                Text("show the alert!")
            }
            Spacer()
        }.alert(isPresented: $shouldShowAlert, content: {

            // what to add here?
            Alert(title: Text("Alert:"), message: Text("press OK to execute onAlertDismissed()..."))

            // what I have tried and doesn't work:
            /*
             Alert(title: Text("Alert:"), message: Text("press OK to execute onAlertDismissed()..."), dismissButton: self.dismissButton as? Alert.Button)
             */


        })

    }
}

person Nerdy Bunz    schedule 18.08.2019    source источник


Ответы (3)


Кнопка устроена несколько иначе. По сути, вам нужно использовать статический фабричный метод из Alert.Button, чтобы создать их и передать их.

Alert(title: Text("Alert:"),
    message: Text("press OK to execute default action..."),
    dismissButton: Alert.Button.default(
        Text("Press ok here"), action: { print("Hello world!") }
    )
)

Alert(title: Text("Alert!"), message: Text("Message"),
    primaryButton: Alert.Button.default(Text("Yes"), action: {
        print("Yes")
    }),
    secondaryButton: Alert.Button.cancel(Text("No"), action: {
        print("No")
    })
)
person Fabian    schedule 18.08.2019
comment
А, значит, я использовал Button, когда мне следовало использовать Alert.Button. Благодарность! - person Nerdy Bunz; 19.08.2019

Можно создавать такие оповещения:

import SwiftUI

struct ContentView: View {

@State var showingAlert = false

var body: some View {
    VStack {
        HStack { 
                Button(action: {
                    self.showingAlert = true
            })
            {
                Text("Save")
                    .font(.headline)
            }
            .alert(isPresented: $showingAlert, content: { 
                return Alert(title: Text("Save Product"), message: Text("Are you sure you want to save the changes made?"), primaryButton: .default(Text("Yes"), action: {
                    //insert an action here
                }), secondaryButton: .destructive(Text("No")))
                })
            }
        }
    }
}
person Oliver    schedule 20.01.2020

Глядя на свой код, кажется, что вы не включаете кнопку в свойство предупреждения, поэтому ваше предупреждение не выполняет никаких действий, в swiftui подпись предупреждения

init(title: Text, message: Text? = nil, primaryButton: Alert.Button, secondaryButton: Alert.Button)

Правильная реализация подписи - это первый шаг

person brianoqr    schedule 18.08.2019