Swift・iOS

Swiftを中心に学んだことを記録に残すブログです。技術に関係ない記事もたまに書いています。

【SwiftUI】アラートを表示する

 

はじめに

アラートを表示する手順をまとめました。

 

開発環境

 

手順

ContentView.swiftを開いて、Textを削除。

ContentView.swift

f:id:hfoasi8fje3:20201218183041p:plain

 

画面右上の"+"を選択。

f:id:hfoasi8fje3:20201218183254p:plain

 

"Button"を選択。

f:id:hfoasi8fje3:20210309221608p:plain

 

コードが挿入される。

ContentView.swift

f:id:hfoasi8fje3:20210309221705p:plain

 

Textを追加することでButtonに表示する文字列を指定。

アラートの表示状態を管理する変数isAlertActiveを追加。

Buttonを選択した時にisAlertActiveをtrueに変更する。

ContentView.swift

f:id:hfoasi8fje3:20210317224134p:plain

 

"alert(isPresented:content:)"を追加。

※参考:https://developer.apple.com/documentation/swiftui/view/alert(ispresented:content:)

ContentView.swift

f:id:hfoasi8fje3:20210317224651p:plain

 

変数isAlertActiveがtrueになった時に、アラートを表示する。

ContentView.swift

f:id:hfoasi8fje3:20210317225253p:plain

 

"Alert"を追加。

※参考:https://developer.apple.com/documentation/swiftui/alert

ContentView.swift

f:id:hfoasi8fje3:20210317225851p:plain


 ビルドしてボタンを選択するとアラートが表示される。

f:id:hfoasi8fje3:20210317230309p:plain

 

アラートのボタンを選択した際に処理を実行したい場合は、"init(title:message:primaryButton:secondaryButton:)"を以下のように実装する。

※参考:

https://developer.apple.com/documentation/swiftui/alert/init(title:message:primarybutton:secondarybutton:)

ContentView.swift

f:id:hfoasi8fje3:20210317231327p:plain

 

外観は以下のようになる。

f:id:hfoasi8fje3:20210317231643p:plain

 

全体のコード

ContentView.swift

import SwiftUI

struct ContentView: View {
    @State var isAlertActive = false
    
    var body: some View {
        Button(action: {
            self.isAlertActive = true
        }) {
            Text("Alertを表示する")
        }
        .alert(isPresented: $isAlertActive, content: {
            Alert(title: Text("エラータイトル"),
                  message: Text("エラーメッセージ"),
                  primaryButton: .default(Text("OK"), action: {
                    print("OKを選択した時の処理をここに実装する")
                  }),
                  secondaryButton: .cancel(Text("キャンセル"), action: {
                    print("キャンセルを選択した時の処理をここに実装する")
                  })
            )
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

おわりに

SwiftUIの基本的な実装の手順は、プログラミングを始めた頃の自分でも分かるように極力細かめに記載することを意識しているのですが、別にAppleのドキュメント見ればすぐに分かるかもしれないという気持ちになりつつあります・・・。

自分の復習用(思い出す用)に記事にまとめている目的もあるので、今後もこのような記事がいくつか続きそうですが、少しでも参考になることがあればと思います。

 

参考