Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to change tint color for View.

What I got:

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

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

like image 661
Sergey Udalov Avatar asked Oct 20 '25 10:10

Sergey Udalov


1 Answers

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.

like image 180
Sweeper Avatar answered Oct 22 '25 04:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!