vendredi 22 mai 2020

Understanding problems with communications patterns > Preference Key in SwiftUI

I've literally just started to play around with SwiftUI so please excuse if this question is stupid. I'm trying since days, read many different posts and tried to follow the official documentation on apple.com but unfortunately can't get my head around how Preference Keys work in SwiftUI.

Basically my test-application ist structured in 3 different components:

Content View
// contains a form and a text field in an HStack

    ∟ Form View
      // contains the form blocks in a TabView

          L Form Block View
            // contains the form fields

What I want to achieve is an information flow from the actual form fields up to the main view which then updates the text field. From what I've read so far, it seems that PreferenceKey is the best option for this problem. Thus my block view looks as follows:

import SwiftUI

// The preference key
struct MyTextPreferenceKey: PreferenceKey {
    static var defaultValue: MyTextPreferenceData?

    static func reduce(value: inout MyTextPreferenceData?, nextValue: () -> MyTextPreferenceData?) {
        value = nextValue()
    }
}

// The data for the from field block
struct MyTextPreferenceData: Equatable {
    var firstName: String
    var lastName: String
}

// The test form block
struct TestFormBlock: View {

    @State private var firstName = MyTextPreferenceData(firstName: "")
    @State private var lastName = MyTextPreferenceData(lastName: "")

    var body: some View {
       Form {
        TextField("First Name", text: $test.firstName) // this would work if firstName would be declared as String
            .preference(key: MyTextPreferenceKey.self, value: self.fistName) // how would I set the Preference Key value here?

        TextField("Last Name", text: $test.lastName)
            .preference(key: MyTextPreferenceKey.self, value: self.lastName)
       }.padding()
    }
}

struct TestFormBlock_Previews: PreviewProvider {
    static var previews: some View {
        TestFormBlock()
    }
}

Again, I'm sorry if this is a stupid question but I'm really stuck and simply can't get my head around how this works...

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire