5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🚨SwiftUIのAlertに.accentColorが効かない→効かせる方法、あります。

Last updated at Posted at 2025-06-17

❓問題:Alertのボタンに.accentColorが反映されない!

たとえば以下のように .tint() や .accentColor() を指定していても…

.alert(isPresented: $showingAlert) {
    Alert(
        title: Text("注意"),
        message: Text("これはデフォルトのAlertです。"),
        dismissButton: .default(Text("OK"))
    )
}

❌ OK ボタンの色は変わらない。
❌ .accentColor が効いてくれない。

「SwiftUIってカスタマイズできないのか…」と諦めてませんか?

✅ 解決方法:新構文で自前でButtonを書く

答えはシンプル。

.alert("ご確認ください", isPresented: $showDuplicateAlert) {
    Button("OK", role: .cancel) { }
} message: {
    Text(".accentColor、効いてますよね?")
}

これだけで、View階層に設定した .tint() や .accentColor() がAlertのボタンに反映されるようになります。

🎨 なぜ効くの?

Alert(title:message:dismissButton:) など旧来のスタイルは、内部的にUIKitの UIAlertController に近く、色のオーバーライドが効きにくい。

一方で、alert(_:isPresented:actions:message:) の新しい構文は、SwiftUIネイティブのButton構造が使われるため、.tint() が適用可能。

つまり…

✅ 自前で Button を書くことで、アクセントカラーが継承される!

💡応用例:AccentColorをカスタマイズ可能にしている場合

.tint(Color(hex: AppSettings.customBackgroundAccentColorHex))

このようなアプリ設定に連動するカスタムカラーでも、Alertのボタンに反映されます。
UIの一貫性を大事にしたい人には最高。

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?