3

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

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Sergey Udalov
  • 75
  • 1
  • 7
  • Sometimes, I find that `foregroundColor` works when `tint` doesn't. If that works, you might even be able to get rid of the `#available` check, since `foregroundColor` is available on iOS 14. – Bbrk24 Oct 21 '22 at 14:02
  • Hi @Bbrk24. It is my pet-project, I have got min 14 iOS. ) btw I've checked foreground color too, and it doesn't worked... – Sergey Udalov Oct 21 '22 at 14:24
  • If you want to use the same accent color everywhere, you can change the Accent Color in your app's asset catalogue. If not, then I don't have an answer for you. – Bbrk24 Oct 21 '22 at 14:30

1 Answers1

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thank u! that's work! But why they write "Use this method to override the default accent color for this view" ? .accentColor != tint accentColor's ? Too many "accent colors" to understanding... ) – Sergey Udalov Oct 21 '22 at 15:13
  • 1
    @SergeyUdalov After the `accentColor` modifier is deprecated, you can think of the `accentColor` *property* as get-only. The system decides what the most appropriate tint color is, depending on the user's settings and preferences. On the other hand, the `tint` modifier allows you to set your own tint color. This is not the user's preference (it is *your* preference!), so it is not the same as `accentColor`. – Sweeper Oct 21 '22 at 15:17