我有一個當前回傳 LinearGradient 作為背景顏色的函式。我想根據變數的值修改回傳型別,使回傳型別是 LinearGradient 或 AngularGradient?
這是我的代碼:
func colors() -> LinearGradient {
return LinearGradient(
gradient: Gradient(colors: [
Color(red: 135/255, green: 206/255, blue: 235/255),
Color(red: 255/255, green: 160/255, blue: 122/255)
]),
startPoint: .topLeading,
endPoint: .top
)
}
相反,我想做這樣的事情:
enum BackgroundType {
case linear
case angular
}
然后執行以下操作:(該函式在 .background() 修飾符中使用)
func colors(backgroundColor: BackgroundType) -> ShapeStyle {
if backgroundColor == .linear {
return LinearGradient(
gradient: Gradient(colors: [
Color(red: 135/255, green: 206/255, blue: 235/255),
Color(red: 255/255, green: 160/255, blue: 122/255)
]),
startPoint: .topLeading,
endPoint: .top
)
} else {
return AngularGradient(gradient: Gradient(colors: [
Color(red: 135/255, green: 206/255, blue: 235/255),
Color(red: 255/255, green: 160/255, blue: 122/255)
]),
center: .topLeading,
angle: .degrees(180 45))
}
請問有什么建議嗎?謝謝!
uj5u.com熱心網友回復:
把你的colors函式變成一個ViewBuilder. 添加@ViewBuilder、回傳some View和洗掉return陳述句。然后此函式將根據以下內容回傳適當View的backgroundColor:
@ViewBuilder
func colors(backgroundColor: BackgroundType) -> some View {
if backgroundColor == .linear {
LinearGradient(
gradient: Gradient(colors: [
Color(red: 135/255, green: 206/255, blue: 235/255),
Color(red: 255/255, green: 160/255, blue: 122/255)
]),
startPoint: .topLeading,
endPoint: .top
)
} else {
AngularGradient(gradient: Gradient(colors: [
Color(red: 135/255, green: 206/255, blue: 235/255),
Color(red: 255/255, green: 160/255, blue: 122/255)
]),
center: .topLeading,
angle: .degrees(180 45))
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516014.html
