Как мне использовать частные переменные состояния для детского просмотра в Swiftui?

Итак, я создаю это приложение, в котором пользователь выбирает таблицу умножения, на которой он хочет попрактиковаться, и количество вопросов в первом просмотре, а затем, нажимая кнопку,

он переходит к следующему представлению, которое передает эти данные, которые затем создают банк вопросов для него.

Возникла ошибка, в которой говорится, что я не могу передать частную переменную, почему это так? Я прикрепил свой код для справки

      import SwiftUI


struct ContentView: View {
    
    @State private var multiplicationTable = 1
    @State private var amountQuestions = 1
  
    
    let multiplicationTables = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    let amountQuestionss = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    var body: some View {
        NavigationView {
            
            VStack {
                
                Picker(selection: $multiplicationTable, label: Text("multiplicationTable")) {
                    ForEach(0 ..< 10) {num in
                        Text("\(multiplicationTables[num])")
                    }
                }
                .padding()
                .padding()
                Text("Choose number of Questions")
                Picker("Select number of questions", selection: $amountQuestions) {
                    ForEach(0 ..< 10) {num in
                        Text("\(amountQuestionss[num])")
                    }
                }
                
                NavigationLink(destination: kek(One: multiplicationTable, Two: amountQuestions)  .navigationBarHidden(true)) {
                    Button ("GO") {
                       
                          
                        
                    }
                    .padding(50)
                    .background(Color.red)
                    .foregroundColor(.white)
                    .clipShape(Circle())
                    
                }
                .navigationTitle("Choose Multiplication Table")
                .navigationBarTitleDisplayMode(.inline)
                
              
                
            }
            
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

это первое представление, вот второе представление

      import SwiftUI

struct kek: View {
    
    let One : Int
    let Two : Int
    
    @State  var Question : String

    @State  var answer = ""
    @State  var Three = 0
    @State  var Four = 0
    
    
    func nextQuestion(){
       Three = One
        Four = Int.random(in: 0...10)
        
        Question = "\(Three) * \(Four)"
        
    }
    
    
    var body: some View {
        VStack {
            
            Text("Question: What is \(Question)?")
            Form {
                Section {
                    TextField("Amount", text: $answer)
                        .keyboardType(.decimalPad)
                    
                    
                }
                
            }
          
                Button ("Next") {
                   
                      
                    
                }
                .padding(50)
                .background(Color.red)
                .foregroundColor(.white)
                .clipShape(Circle())
                
            
            
            
        }
        
    }
}



struct kek_Previews: PreviewProvider {
    static var previews: some View {
        kek(One: 1, Two: 2)
    }
}

1 ответ

Решение

Я не уверен, где вы получаете ошибку, так как можно передать переменную в другое представление. Я изменил ваш код, чтобы проиллюстрировать то, что, по моему мнению, вы пытаетесь достичь.

Вы заметите в kek вид я изменил твою @State var question: String к var question: Int так как Int передается.

      struct ContentView: View {

@State private var multiplicationTable = 1
@State private var amountQuestions = 1

let multiplicationTables = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let numberOfQuestions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var body: some View {
    NavigationView {

        VStack {
            Picker("Multiplication Table", selection: $multiplicationTable) {
                // There was an "off by one" issue in the kek View which I resolved by using the value of the array itself for the selection. Not the location in the array.
                ForEach(multiplicationTables, id: \.self) { num in
                    Text("\(num)")
                }
            }
            .pickerStyle(.segmented)
            .padding([.top, .bottom], 20)
            /*
             Don't use
                .padding()
                .padding()
             Instead you can specify how large you'd like the padding to be around the view.
             */
            Text("Choose number of Questions")
            Picker("Select number of questions", selection: $amountQuestions) {
                ForEach(0 ..< numberOfQuestions.count) {num in
                    Text("\(numberOfQuestions[num])")
                }
            }

            NavigationLink {
                kek(one: multiplicationTable, two: amountQuestions, question: multiplicationTable)
            } label: {
                // A NavigationLink is clickable by default, so you don't need to place a Button inside of it.
                // Here I used Text and formatted it just as you had with your Button.
                Text("Go")
                    .padding(50)
                    .background(Color.red)
                    .foregroundColor(.white)
                    .clipShape(Circle())
            }
            .navigationTitle("Choose Multiplication Table")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
  }
}

struct kek: View {
    let one: Int
    let two: Int // note: It doesn't look like you're actually using this property. Consider removing it.

    var question: Int

    @State private var answer = ""
    @State private var randomNumber = 0


    func nextQuestion(){
        randomNumber = Int.random(in: 0...10)
    }


    var body: some View {
        VStack {

            Text("Question: What is \(question) * \(randomNumber)?")
            Form {
                Section {
                    TextField("Amount", text: $answer)
                        .keyboardType(.decimalPad)
                }
            }
            Button ("Next") {
                nextQuestion()
            }
            .padding(50)
            .background(Color.red)
            .foregroundColor(.white)
            .clipShape(Circle())
        }

   } 
}
Другие вопросы по тегам