Leaves One

Alan Richard's Blog

SwiftUI: Fix Alert and ActionSheet Buttons Not Using Accent Color by Default

Problem

SwiftUI alert's buttons not using accent color by default

SwiftUI action sheet's buttons not using accent color by default

In some cases, SwiftUI’s Alert and ActionSheet buttons don’t use accent color by default unless users tap & move their finger on them. This is weird and buggy.

Attempt

It’s attempting to add the following constructor to the struct with @main attribute:

init {
UIView.appearance().tintColor = UIColor(named: "AccentColor")
}

But without specifying the containerTypes parameter in UIView.appearance(), it will affect other views as well. For example, the foreground color of swipe actions in List will also be changed to the accent color, which is not what we want.

Wrongly changed foreground color of swipe actions in List

Docs: appearance(whenContainedInInstancesOf:)

Solution

Be more specific about the container types:

init {
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self])
.tintColor = UIColor(named: "AccentColor")
}

SwiftUI alert's buttons using accent color by default

Notice that by specifying the container types as above, the foreground color navigation items will be set to the default blue.

Add .tint(.accentColor) will fix this:

var body: some Scene {
WindowGroup {
ContentView()
.tint(.accentColor) // <--- Add this
}
}

You may also want to define tint color for swipeActions buttons (a simple .tint(_:) will work).

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
If you checked “Remember me”, your email address and name will be stored in your browser for your convenience.