gpt4 book ai didi

ios - 如何比较两个线性梯度?用户界面

转载 作者:行者123 更新时间:2023-12-01 19:35:26 29 4
gpt4 key购买 nike

我有多个渐变作为我的应用程序的主题。当渐变(存储在变量中)是特定的时,我想要一个 bool 值变为真。但是,我不断收到错误消息:

"Binary operator '==' cannot be applied to two 'LinearGradient' operands"



请帮忙!

这是我的代码:
let pinkGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 123/255, green: 30/255, blue: 122/255), Color(red: 248/255, green: 74/255, blue: 167/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)  
let blueGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 0/255, green: 52/255, blue: 89/255), Color(red: 0/255, green: 168/255, blue: 232/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)
let yellowGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 240/255, green: 30/255, blue: 50/255), Color(red: 255/255, green: 189/255, blue: 0/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)


if userData.selectedTheme == pinkGradient { //This is where the error occurs
self.isPinkThemeSelected = true
} else if userData.selectedTheme == blueGradient { //This is where the error occurs
self.isBlueThemeSelected = true
} else {
self.isYellowThemeSelected = true
}

最佳答案

您不能直接执行此操作。大多数 SwiftUI View 都是“只写”的。一旦你创建了它们,你就不能问它们是如何创建的。 (Path 是此规则的一个显着异常(exception)。)

相反,我建议将您的状态与渐变 View 本身隔离开来。例如,您可以创建一个 Theme结构如:

struct Theme: Identifiable {
let id = UUID() // This ensures that even two themes with the same name are unique
let name: String // This is just for your convenience
let gradient: LinearGradient
}

extension Theme: Equatable {
static func == (lhs: Theme, rhs: Theme) -> Bool { lhs.id == rhs.id }
}

let pinkTheme = Theme(name: "pink",
gradient: LinearGradient(gradient: Gradient(colors:[
Color(red: 123/255, green: 30/255, blue: 122/255),
Color(red: 248/255, green: 74/255, blue: 167/255)]),
startPoint: .bottomLeading, endPoint: .topTrailing))

let blueTheme = Theme(name: "blue",
gradient: LinearGradient(gradient: Gradient(colors:[
Color(red: 0/255, green: 52/255, blue: 89/255),
Color(red: 0/255, green: 168/255, blue: 232/255)]),
startPoint: .bottomLeading, endPoint: .topTrailing))

现在您可以跟踪 selectedThem == pinkTheme .

如果您有固定数量的主题,您还可以更简单地将其实现为枚举:
enum Theme: Equatable {
case pink
case blue
case yellow

var gradient: LinearGradient {
switch self {
case .pink: return LinearGradient(gradient: Gradient(colors:[
Color(red: 123/255, green: 30/255, blue: 122/255),
Color(red: 248/255, green: 74/255, blue: 167/255)]),
startPoint: .bottomLeading, endPoint: .topTrailing)
case .blue: ...
case .yellow: ...
}
}
}

关于ios - 如何比较两个线性梯度?用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60367808/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com