SwiftUI 无法更改类方法的颜色按钮



我创建了一个KetupatButton类,其中有两个方法,如下所示:

class KetupatButton {
var condition = false
@State var colorToShow = Color(UIColor(red: 183/255, green: 191/255, blue: 150/255, alpha: 100))
func colorChange() {
if condition == false {
colorToShow = Color(UIColor(red: 183/255, green: 191/255, blue: 150/255, alpha: 100))
} else {
colorToShow = Color(UIColor(red: 19/255, green: 58/255, blue: 27/255, alpha: 100))
}
}
func createButton(size: CGFloat) -> some View {
return AnyView(Button(action: {
self.condition = !self.condition
self.colorChange()
print(self.colorToShow)
print(self.condition)
}, label: {
Rectangle()
.frame(width: size, height: size, alignment: .leading)
.foregroundColor(colorToShow)
}))
}

}

但是,当我从ContentView调用该类并点击按钮时,按钮不会改变它的颜色。即使当我打印colorToShow变量时,它也发生了变化。但是按钮的UI颜色没有改变。。。

这是我的ContentView

struct ContentView: View {
var button1 = KetupatButton()
var body: some View {
button1.createButton(size: 200)
}

}

您应该采用更结构化的方法:将您的视图模型(即您的类(与视图分离。以下是一些步骤:

  1. 如果可以避免的话,视图模型不应该包含视图。创建一个特定的视图来显示按钮,与逻辑分离。以下是您的按钮的外观:
struct ButtonView: View {

// Receive the view model
@ObservedObject var viewModel: KetupatButton
let size: CGFloat

var body: some View {
Button {
// Use this to animate the change
withAnimation {
// The condition will automatically change the color, see the view model code
viewModel.condition.toggle()
}
} label: {
Rectangle()
.frame(width: size, height: size, alignment: .leading)
.foregroundColor(viewModel.colorToShow)
}
}
}
  1. 您的视图模型应该是一个Observable Object。此外,触发UI更改的值应该是@Published变量。此外,我还做了一种方法,当条件改变时,颜色会自动改变,这样你就可以摆脱colorChnage()
class KetupatButton: ObservableObject {

// When this variable changes, it will change also the color.
var condition = false {
didSet {
if condition {
colorToShow = Color(UIColor(red: 19/255, green: 58/255, blue: 27/255, alpha: 100))
} else {
colorToShow = Color(UIColor(red: 183/255, green: 191/255, blue: 150/255, alpha: 100))
}
}
}
@Published var colorToShow = Color(UIColor(red: 183/255, green: 191/255, blue: 150/255, alpha: 100))
}
  1. 最后,ContentView应该创建一个视图模型的实例作为@StateObject与子视图共享,如我们上面创建的ButtonView
struct ContentView: View {
@StateObject var viewModel = KetupatButton()
var body: some View {
ButtonView(viewModel: viewModel, size: 200)
}
}

现在,您可以看到按钮的颜色发生了变化。

最新更新