LoginSignup
2
6

More than 1 year has passed since last update.

【SwiftUI】アラートがなんか使いずらい

Last updated at Posted at 2022-05-02

標準アラート

import SwiftUI

struct ContentView: View {
    @State var ShowAlert: Bool = false
    var body: some View {
        VStack {
            Button("アラート表示") {
                ShowAlert.toggle()
            }
        }
        .alert(isPresented: $ShowAlert) {
            Alert(title: Text("アラート"), message: Text("アラートが表示されました。"), dismissButton: .default(Text("OK")))
        }
    }
}

カスタムアラート

import SwiftUI

struct ContentView: View {
    @State var ShowAlert: Bool = false
    var body: some View {
        VStack {
            Button("アラート表示") {
                alert(title: "アラート", message: "アラートが表示されました。") {
                    print("アクションが実行されました")
                }
            }
        }
    }
    func alert(title: String?, message: String?, action: @escaping () -> Void) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultButton = UIAlertAction(title: "OK", style: .default) { _ in
            action()
        }
        alert.addAction(defaultButton)
        UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

注意
iOS15からUIApplication.shared.windowsが非推奨に変わったのでiOS15以降で使用する場合は1番下の行に警告が出ます。
以下の記事を参考に推奨コードに変更してください。

https://qiita.com/SNQ-2001/items/b14aff80c3038a98129f

これを追加することでボタンの数を増やせます。

let Action1 = UIAlertAction(title: "OK", style: .default) { _ in
    // アクション
}
let Action2 = UIAlertAction(title: "Cancel", style: .cancel) { _ in
    // アクション
}
alert.addAction(Action1)
alert.addAction(Action2)
style
// 青細文字
.default
// 細文字
.destructive
// 青太文字
.cancel

おわり

1年前くらいに一定条件下でSwiftUI標準アラートが出ないバグに遭遇して以来、
私はずっと下を使っています。

標準の方はトリガーとアラート本体が別の場所にあってコード量が増えてくると「これなんのアラートだっけ」みたいな感じによくなってました笑(コメント書いとけって話ですが...)

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6