【发布时间】:2020-04-12 09:01:48
【问题描述】:
我有来自 Swift UI 的 Color 库作为我的视图状态的一部分。我在初始化视图时尝试设置视图的颜色,但颜色设置不正确。
这是我的代码:
struct CalcButtonView: View {
var calcButton: CalcButton
var highlightAble: Bool = false
@State var foregroundColor: Color? = nil
@State var backgroundColor: Color? = nil
@State private var highlighted: Bool = false
@EnvironmentObject var numObservable: NumObservable
init(newCalcButton: CalcButton){
/// Buttons that are light gray
let lightGrayButtons: [String] = ["C", "+/-", "%"]
/// Buttons that are orange
let orangeButtons: [String] = ["/", "x", "-", "+", "="]
self.calcButton = newCalcButton
self.highlighted = false
self.foregroundColor = Color.white
if lightGrayButtons.contains(self.calcButton.label){
self.backgroundColor = Color.lightGray
self.highlightAble = false
} else if orangeButtons.contains(self.calcButton.label){
self.backgroundColor = Color.orange
self.highlightAble = true
} else {
self.backgroundColor = Color.darkGray
self.highlightAble = false
}
}
}
结果是,当我的前景被明确设置为白色而我的背景颜色不应该是黑色时,我的所有背景颜色都恢复为蓝色,前景色为蓝色。
我认为这与我的 Color 结构设置为 nil 有关。想法?
根据要求,这是我的body 实现:
var body: some View {
Button(action: {
self.numObservable.updateOrOperationDelegate(buttonLabel: self.calcButton.label)
self.toggleHighLight()
}, label:{
Text(calcButton.label)
.background(self.backgroundColor)
.foregroundColor(self.foregroundColor)
.cornerRadius(75)
})
}
更新#2:经过更多测试,我发现我的变量foregroundColor 和backgroundColor 仍然是nil,即使在我的init 函数运行之后。有谁知道怎么可能?
【问题讨论】:
-
你能告诉我们你的
body实现吗? -
@Palle 我添加了我的身体。