我对 SwiftUI 相当陌生,遇到了以下问题:
我有一个包含一些整数值的模型,如下所示:
class Game: ObservableObject {
@Published var ownScore:Int = 0
@Published var opponentScore:Int = 0
... some methods
}
Run Code Online (Sandbox Code Playgroud)
我还需要一个视图来显示这些分数,并在这些值发生变化时进行更新。我需要类似的东西,但是,这不起作用,因为这些值是发布的整数。
struct ScoreView: View {
@EnvironmentObject var game: Game
@State var displayOpponent: Bool
var body: some View {
VStack {
if displayOpponent {
Text("Opponent Score")
Text("Score: \(game.$opponentScore)")
} else {
Text("Your Score")
Text("Score: \(game.$ownScore)")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
关于如何正确实施这一点有什么想法吗?
我目前正在开发一个应用程序,向用户显示他的植物箱和一些测量值(如地面湿度、温度等)。每个植物箱里面都有一些植物,这些植物以详细视图显示。我希望用户能够将其中一株植物拖到角落以将其移除。目前我有这个实现:
@GestureState private var dragOffset = CGSize.zero
var body: some View {
//Plants Headline
VStack (spacing: 5) {
Text("Plants")
.font(.headline)
.fontWeight(.light)
//HStack for Plants Images
HStack (spacing: 10) {
//For each that loops through all of the plants inside the plant box
ForEach(plantBoxViewModel.plants) { plant in
//Image of the individual plant (obtained via http request to the backend)
Image(base64String: plant.picture)
.resizable()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 2))
.offset(x: self.dragOffset.width, y: self.dragOffset.height)
.animation(.easeInOut)
.aspectRatio(contentMode: .fill)
.frame(width: 70, height: 70)
.gesture(
DragGesture()
.updating(self.$dragOffset, body: …Run Code Online (Sandbox Code Playgroud)