我有以下代码:
struct TestContainer: View {
@State var useGradient = false
var body: some View {
ZStack {
Color.black
Button {
} label: {
RoundedRectangle(cornerRadius: .infinity)
.fill(useGradient ? buttonGradient() as! Color : Color.green)
.overlay {
Text("Done")
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(.white)
}
.cornerRadius(.infinity)
}
.frame(height: 44)
.padding(.horizontal, 40)
}
}
private func buttonGradient() -> some View {
return LinearGradient(
stops: [
Gradient.Stop(color: Color(red: 0.1, green: 0.2, blue: 0.2), location: 0.00),
Gradient.Stop(color: Color(red: 0.1, green: 0.3, blue: 0), location: 1.00),
],
startPoint: UnitPoint(x: 0, y: 1),
endPoint: UnitPoint(x: 1, y: 0)
)
}
}
有时我会
Could not cast value of type 'SwiftUI.LinearGradient' (0x1f2bf7980) to 'SwiftUI.Color' (0x1f2c1b688).
我怎样才能根据填充变化的
useGradient
状态来完成这项工作?
A
LinearGradient
无法转换为 Color
。它们的共同祖先是ShapeStyle
协议。
由于您需要在
.fill()
方法中返回单一类型,因此您必须将擦除 Color
和 LinearGradient
键入为单一样式,您可以使用 AnyShapeStyle
: 来完成此操作
.fill(useGradient ? AnyShapeStyle(buttonGradient()) : AnyShapeStyle(Color.green))
但是您应该从
some ShapeStyle
返回 some View
而不是 buttonGradient()
。