给HStack中的项目添加线性颜色渐变?

问题描述 投票:0回答:1

在SwiftUI中是否有办法为HStack中的所有项目添加渐变色。

enter image description here

你可以在HStack和HStack中应用一个单独的颜色。.background.foregroundColor 但由于LinearGradient是一个符合View的结构,你不能将它传递给 .foregroundColor 因为它期待的是一个Color。

你可以用不同的方法来解决这个问题(下面是一个使用不透明度的例子),但是我很好奇,这么多的SwiftUI选项,我是不是还漏了什么?

SwiftUI示例 :

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输出 。

enter image description here

ios swiftui linear-gradients hstack
1个回答
1
投票

有内置的渐变......如何呈现它是由我们决定的......。这里有一个可能的替代方案,但它只是... ...许多其他变体中的一个,你知道的。

demo

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))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.