简体   繁体   中英

LinearGradient on TabItem in TabView SwiftUI

Is it possible to apply a LinearGradient to a TabItem? AccentColor only takes a color, and I haven't found another way to apply any color to a TabItem. Any Ideas?例如,这是从蓝色到绿色的渐变(This in a Gradient from blue to green, for example)

There is no chance to apply gradient in SwiftUI for the accentColor. So in your case you will have to create your own Tab Bar Items Images with a gradient and save them as a png. You will have to match the sizes, as you can not resize Image inside tabItem. See this answer for the sizes

You will need an active Image with your gradient and a inactive Image maybe gray like the default TabBar behavior. Then just load your Images in the TabView and depending on the selection..

Here is an example

struct ContentView: View {
    @State var selection = 0
    var body: some View {
        TabView(selection: $selection) {
            Text("First")
                .tabItem {
                    Image(selection == 0 ? "home_active" : "home_inactive") //<< here you load your different images 

                    Text("Home")
                        .colorMultiply(Color.yellow)
                }

            Text("Second")
                .tabItem {
                    Image(selection == 1 ? "setting_active" : "setting_inactive")
                    Text("Setting")
                }
        }
    }
}

在此处输入图像描述

Yes we cannot apply gradient on tabItem in SwiftUI. It only shows no more than one Image and one Text view, although we have put more views inside.tabItem{}.

So that you have to make custom tab bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM