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 pass values in Views in SwiftUI #449

Open
MaksimBezdrobnoi opened this issue Jan 28, 2023 · 2 comments
Open

How to pass values in Views in SwiftUI #449

MaksimBezdrobnoi opened this issue Jan 28, 2023 · 2 comments

Comments

@MaksimBezdrobnoi
Copy link

How you pass values from view to another view in needle? In your examples you use dependency ViewModel, but what if I need to pass some value to init ViewModel? How to do that?

@bohdansasko
Copy link

Could you clarify your question with an example(s)?

@MarcelDerks
Copy link

MarcelDerks commented Nov 30, 2023

struct AddressesView<ViewModel>: View where ViewModel: AddressesViewModelProtocol {
    @ObservedObject var viewModel: ViewModel

    var detailBuilder: AddressDetailBuilder
    
    var body: some View {
        NavigationView {
            List(viewModel.addresses) { address in
                NavigationLink(destination: detailBuilder.addressDetailView) {
                    AddressRow(address: address)
                }
            }
            .navigationTitle("Address List")
        }
    }
}

Maybe it is meant like this.
How would you pass the selected address down the line here to AddressDetailView ?
Of course you can keep it somewhere globally or in shared instances, but for cases like this it seems to be a bit over the top.
So is there any way to pass values ?

Maybe like this ?

import NeedleFoundation
import SwiftUI

protocol AddressDetailDependency: Dependency {
    var addressRepository: AddressRepository { get }
}

class AddressDetailComponent: Component<AddressDetailDependency>, AddressDetailBuilder {
    
    func addressDetailViewModel(selectedId: UUID) -> AddressDetailViewModel {
        AddressDetailViewModel(repository: dependency.addressRepository, selectedId: selectedId)
    }
    
    func addressDetailView(selectedId: UUID) -> AnyView {
        AnyView(
            AddressDetailView(viewModel: addressDetailViewModel(selectedId: selectedId))
        )
    }
}

protocol AddressDetailBuilder {
    func addressDetailView(selectedId: UUID) -> AnyView
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants