问题
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