Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to modify data inside array in SwiftUI #516

Open
onmyway133 opened this issue Nov 22, 2019 · 0 comments
Open

How to modify data inside array in SwiftUI #516

onmyway133 opened this issue Nov 22, 2019 · 0 comments
Labels

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Nov 22, 2019

Suppose we have an array of SearchObject, and user can enter search query into text property.

class SearchObject: ObservableObject {
    let name: String
    let search: (String) -> [Country]
    var text: String = ""

    init(name: String, search: @escaping (String) -> [Country]) {
        self.name = name
        self.search = search
    }
}

Although SearchObject is class, when we use ForEach, the changes to passed object won't be reflected in our array and there is no reload trigger, we need to point to object in array directly, like

self.$searchObjects[index].text
struct SearchScreen: View {
    @State var searchObjects: [SearchObject] = [
        SearchObject(name: "By name", search: { CountryManager.shared.search(byName: $0) }),
        SearchObject(name: "By calling code", search: { CountryManager.shared.search(byCallingCode: $0) }),
        SearchObject(name: "By domain", search: { CountryManager.shared.search(byDomain: $0) }),
        SearchObject(name: "By language", search: { CountryManager.shared.search(byLanguage: $0) })
    ]

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                ForEach(searchObjects.enumerated().map({ $0 }), id: \.element.name, content: { index, searchObject in
                    VStack(alignment: .leading) {
                        Text(searchObject.name)
                            .styleLabel()
                        TextField(searchObject.textFieldName, text: self.$searchObjects[index].text)
                            .styleTitle()
                        self.makeButton(searchObject: self.searchObjects[index])
                    }
                })
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant