Linear Color Gradient to items in HStack?

我的未来我决定 提交于 2020-07-22 06:14:07

问题


Is there a way in SwiftUI to add a gradient color to all items in an HStack.

You can apply an individual Color to both the HStack .background and .foregroundColor But because LinearGradient is a struct that conforms to View you can't pass it to .foregroundColor because it is expecting a Color.

You can work round this in various ways (one example using opacity below) but I was curious with so many SwiftUI options if I was missing something else?

SwiftUI Example :

struct GradView: View {
    var body: some View {
        HStack {
            ForEach((1...5).reversed(), id: \.self) { index in
                RoundedRectangle(cornerRadius: 5)
                    .frame(width: 50, height: 50)
                    .opacity(Double(index) / 5)
            }
        }.foregroundColor(Color.red)
    }
}

SwiftUI Output :


回答1:


There is built-in Gradient... how to present it is up to us... Here is possible alternate, but it is just ... one of many other variants.. you know.

struct GradView: View {
    var body: some View {
        HStack(spacing: 0) {
            ForEach((1...7).reversed(), id: \.self) { index in
                HStack(spacing: 0) {
                    Rectangle().fill(Color.clear)
                        .frame(width: 50, height: 50)
                    Rectangle().fill(Color(UIColor.systemBackground))
                        .frame(width: 4, height: 50)
                }
            }
        }.background(LinearGradient(gradient: 
           Gradient(colors:[.red, .black]), 
                    startPoint: .leading, endPoint: .trailing))
    }
}


来源:https://stackoverflow.com/questions/61542292/linear-color-gradient-to-items-in-hstack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!