Home > Software engineering >  How can I creat struct view in SwiftUI
How can I creat struct view in SwiftUI

Time:10-10

I want to use QuestionView View in two different View. But I have Questions array in 1st View. 2. I have WrongQuestions array in View. I'm passing these arrays into QuestionView with @Binding. I don't want to write the same QuestionView twice. I just want to change the @Binding arrays it will get.

I have two different models. 1. Question 2. WrongQuestion

How can I design QuestionView according to these two different models?

I don't want QuestionView to only get [Question] array. I want it to retrieve [Question] and [WrongQuestion] arrays.

First I want to show QuestionView

I want @Binding var questions: [Question] array in QuestionView to have WrongQuestions in second View. How can I do that ?

QuestionView:

struct QuestionView: View {
    
    @State var selectedQuestion: Int = 1
    @StateObject var questionConfig = QuestionConfig()
    @Binding var questions: [Question] //
    
    var body: some View {
       ...........
    }
}

1. View:

QuizCategoryViewModel:

final class QuizCategoryViewModel: ObservableObject {
       .....
    @Published var selectedQuestion: [Question] = []
       .....
}


struct QuizCategoryView: View {
    
    @StateObject var quizCategoryViewModel: QuizCategoryViewModel = QuizCategoryViewModel()
    
    var body: some View {
        ......
        QuestionView(questions: $quizCategoryViewModel.selectedQuestion)
        ......
    }
}

2. View:

WrongQuestionView:

As seen in the second View it wants me to assign [Question] array, but I want to assign [WrongQuestion] array here. How can I make this generic?

struct WrongQuestionView: View {
    var body: some View {
        QuestionView(questions: <#T##[Question]#>) <---- HERE
    }
}

enter image description here

CodePudding user response:

It looks like there might be some detail missing in the question (like showing Question and WrongQuestion and where the view is that has the array of WrongQuestion), but in a general sense, it sounds like you need a protocol that both Question and WrongQuestion conform to and then a QuestionView that can accept either type.

protocol QuestionType {
    
}

struct Question : QuestionType {
    
}

struct WrongQuestion : QuestionType {
    
}

struct QuestionView<T:QuestionType>: View {
    @Binding var questions: [T]
    
    var body: some View {
       Text("Hi")
    }
}

struct ContentView: View {
    @State var wrongQuestions : [WrongQuestion] = []
    @State var questions : [Question] = []
    
    var body: some View {
        QuestionView(questions: $wrongQuestions)
        QuestionView(questions: $questions)
    }
}
  • Related