SwiftUI View .tint(_ Color) method doesn't work

SwiftUI View .tint(_ Color) method doesn't work

Problem Description:

I’m trying to change tint color for View.

What I got:

    var body: some View {
    Button {
        selectedTab = title
    } label: {
        VStack(alignment: .center) {
        .foregroundColor(selectedTab == title ? .accentColor : .black.opacity(0.2))

The problem:
When I use .accentColor(Color) in superview for this subview, Xcode said:
enter image description here

So, I use, like in docs: apple docs Use this method to override the default accent color for this view. :

            if #available(iOS 15.0, *) {
            CustomTabView(tabs: "").tint(.red)
        } else {
            CustomTabView(tabs: "").accentColor(.green)

Accent color work fine, but .tint doesn’t. What I do wrong?

enter image description here

enter image description here

Solution – 1

Your code doesn’t work because when you use tint, and you select the tab, the tab’s color gets overridden by the foregroundColor modifier. It’d set the tab’s color to .accentColor, which is independent from the color that tint sets. The deprecated accentColor however, does set it, so that’s why the deprecated accentColor modifier works.

One way to work around this is simply not use .accentColor for the foreground color. Use nil instead:

.foregroundColor(selectedTab == title ? nil : .black.opacity(0.2))

When it is nil, it will not override the tint.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.