SwiftUI中是否可以将渐变颜色添加到HStack中的所有项目。
您可以将单独的Color应用于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输出:
最佳答案
有内置的Gradient ...如何呈现它取决于我们...这是可能的替代方法,但这仅仅是...许多其他变体之一..您知道。
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))
}
}
关于ios - 线性颜色渐变到HStack中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61542292/