So I have a ViewA which returns a value called idd
after defining a function addNote()
and I wish to use that idd
value in ViewB. I'm able to define idd
in ViewB as viewA.addNote()
however I'm not able to get the value of idd
passed to viewB. And even Xcode says that my result from addNote() us unused
. I'm new to swiftUI and learning everyday so I'd appreciate if you could let me know how to approach this problem. Thanks!
View A:
class viewA: ObservableObject{
@Published var idd: String = ""
func addNote()-> String{
// some Code
return idd
}
}
View B:
struct ViewB: View {
@StateObject var viewTwo = viewTwo()
@State var idd = String()
var body: some View {
NavigationView {
ZStack{
.navigationTitle("Notes")
.navigationBarItems(
trailing: Button (action: {},
label: { NavigationLink(destination: NoteView(newNote: "", idd: viewA.addNote() ) )
{Image(systemName: "plus")} }
))
.listStyle(.plain)
.buttonStyle(PlainButtonStyle())
}
}
viewA
is your viewModel
for viewB
. So the name of viewA
should be ViewBViewModel
.
class
/struct
names should start with Capital letters.
In your viewModel
(in this case in viewA
) just set a value to your Published
property , it will be auto updated throughout all the Views
where it is being used. In this case:
class viewA: ObservableObject{
@Published var idd: String = ""
func addNote()-> String {
// some Code
self.idd = idd // setting idd here, which will be auto updated (since its a published variable) in the
//views where @Stateobject property wrapper is being used to instantiate viewA
// (which is a viewModel actually).
}
}