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

alert(isPresented:error:actions:)

Presents an alert when an error is present.

Declaration 宣言

func alert<E, A>(isPresented: Binding<Bool>, error: E?, actions: () -> A) -> some View where E : LocalizedError, A : View

Parameters パラメータ

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.

error

An optional localized Error that is used to generate the alert’s title. The system passes the contents to the modifier’s closures. You use this data to populate the fields of an alert that you create that the system displays to the user.

actions

A ViewBuilder returning the alert’s actions.

Discussion 議論

In the example below, a button conditionally presents an alert depending upon the value of an error. When the error value isn’t nil, the system presents an alert with an “OK” action.

The title of the alert is inferred from the error’s errorDescription.


struct TicketPurchaseView: View {
    @Binding var error: TicketPurchaseError?
    @State var showAlert = false
    var body: some View {
        TicketForm(error: $error)
            .alert(isPresented: $showAlert, error: error) {
                Button("OK") {
                    // Handle acknowledgement.
                }
            }
    }
}

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.

This modifier creates a Text view for the title on your behalf, and treats the localized key similar to init(_:tableName:bundle:comment:). See Text for more information about localizing strings. Textを文字列のローカライズについてのさらなる情報として見てください。

See Also 参照

Alerts