如何访问另一个结构中的变量? SWIFTUI

时间:2020-03-11 15:20:02

标签: swiftui

我想访问其他结构中的变量以得到总数。

示例代码会更好地演示:

struct level1: View {

@State var score1 = 5 

}

struct level2: View {

@State var score2 = 7 

}

在另一个结构中,我希望能够使用score1和score2变量。下面的代码不起作用,但是我需要这样的东西。

struct finalScore: View {

@State var totalScore = level1.score1 + level2.score2 

}

2 个答案:

答案 0 :(得分:2)

以不同的方式重新思考它...如下所示,单源信任,模型分离-视图分离,模型更改-视图反应,这就是SwiftUI的方式。

喜欢

import SwiftUI
import Combine

class ScoreModel: ObservableObject {
    @Published var score1 = 5
    @Published var score2 = 7
}

struct MainView: View {
    @ObservedObject var vm: ScoreModel = ScoreModel()

    var body: some View {
        VStack {
            level1(vm: vm)
            level2(vm: vm)
            Divider()
            finalScore(vm: vm)
        }
    }
}
struct level1: View {
    @ObservedObject var vm: ScoreModel

    var body: some View {
        Text("\(vm.score1)")
    }
}

struct level2: View {
    @ObservedObject var vm: ScoreModel

    var body: some View {
        Text("\(vm.score2)")
    }
}

struct finalScore: View {
    @ObservedObject var vm: ScoreModel

    var body: some View {
        Text("\(vm.score1 + vm.score2)")
    }
}

答案 1 :(得分:0)

您需要使用@State&@Binding来完成此操作。这是可以满足您要求的工作代码。

import SwiftUI

struct ContentView: View {

    @State var score1: Int = 5
    @State var score2: Int = 7

    var body: some View {
        VStack {
            HStack {
                FirstView(score1: $score1)
                SecondView(score2: $score2)
                Spacer()
            }
            Divider()
            Text("The total score is \(score1 + score2)")
            Spacer()
        }
        .padding()
    }
}

struct FirstView: View {
    @Binding var score1: Int

    var body: some View {
        Stepper(value: $score1, in: 0...100) {
            Text("\(score1)")
        }
    }
}

struct SecondView: View {
    @Binding var score2: Int

    var body: some View {
        Stepper(value: $score2, in: 0...100) {
            Text("\(score2)")
        }
    }
}

adds score1 and score2 to display total score