[SwiftUI]Alert(アラート)の背景色を変えるには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

alert修飾子で表示するAlertの背景色を変える方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Alertの背景色を変えるには、UIViewを使います。

具体的には、initメソッドやonAppear修飾子などで、「UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).backgroundColor」にAlertの背景色を代入します。

UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).backgroundColor = backgroundColor

「UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).backgroundColor」に代入された色が、Alertの色になります。

UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).backgroundColorは、Alert構造体の色を変えることが出来ません。

有効なのは、alert修飾子のアラートのみです。

使用例

struct ContentView: View {
    @State var showAlert = false
    
    init() {
        UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).backgroundColor = .yellow.withAlphaComponent(0.3)
    }

    var body: some View {
        VStack {
            Button(action: {
                showAlert = true;
            }){
                Text("Show")
            }
            .alert("Title",
                isPresented: $showAlert,
                actions: {
                    Button(action: {}) {Text("Button")}
                },
                message: {
                    Text("This is Alert message")
                }
            )   
        }
    }
}

コメント

タイトルとURLをコピーしました