Instance Method インスタンスメソッド

alert(_:isPresented:actions:message:)

Presents an alert with a message when a given condition is true using a string variable as a title.

Declaration 宣言

func alert<S, A, M>(_ title: S, isPresented: Binding<Bool>, actions: () -> A, message: () -> M) -> some View where S : StringProtocol, A : View, M : View

Parameters パラメータ

title

A text string used as the title of the alert.

isPresented

A binding to a Boolean value that determines whether to present the alert. When the user presses or taps one of the alert’s actions, the system sets this value to false and dismisses.

actions

A ViewBuilder returning the alert’s actions.

message

A ViewBuilder returning the message for the alert.

Discussion 議論

In the example below, a button conditionally presents an alert depending upon the value of a bound Boolean variable. When the Boolean value is set to true, the system displays an alert with an “OK” action.


struct LoginView: View {
    @Binding var didFail: Bool
    var title: String
    var body: some View {
        LoginForm(didFail: $didFail)
            .alert(title, isPresented: $didFail) {
                Button("OK") {
                    // Handle acknowledgement.
                }
            } message: {
                Text("Please ensure your credentials are correct.")
            }
    }
}

All actions in an alert dismiss the alert after the action runs. The default button is shown with greater prominence. You can influence the default button by assigning it the defaultAction keyboard shortcut.

The system may reorder the buttons based on their role and prominence.

If no actions are present, the system includes a standard “OK” action. No default cancel action is provided. If you want to show a cancel action, use a button with a role of cancel.

On iOS, tvOS, and watchOS, alerts only support controls with labels that are Text. Passing any other type of view results in the content being omitted.

Only unstyled text is supported for the message.

See Also 参照

Alerts with a Message