How to bind objects using MVVM design pattern? - ios

I'm trying to change below code(1.) to MVVM architecture(2.) but can't figure out how to bind objects.
I think the problem is FirstView only pass value but not actually a Binding Object, I tried some different ways but always stuck on don't know how to assign Binding Object to #Published.
Could somebody please give a few hints?
(Works fine)
struct FirstView: View {
#State var showSecondView = false
var body: some View {
Button(action: {
self.showSecondView.toggle()
}) {
Text("Show second view")
}
.sheet(isPresented: $showSecondView) {
SecondView(showSecondView: self.$showSecondView)
}
}
}
struct SecondView: View {
#Binding var showSecondView: Bool
var body: some View {
Button(action: {
self.showSecondView.toggle()
}) {
Text("Dismiss")
}
}
}
(MVVM)
struct FirstView: View {
#ObservedObject var vm = FirstViewModel()
var body: some View {
Button(action: {
self.vm.showSecondView.toggle()
}) {
Text("Show second view")
}
.sheet(isPresented: $vm.showSecondView) {
SecondView2(vm: SecondViewModel(showSecondView: self.vm.showSecondView))
}
}
}
class FirstViewModel: ObservableObject {
#Published var showSecondView = false
}
struct SecondView: View {
#ObservedObject var vm: SecondViewModel
var body: some View {
Button(action: {
self.vm.showSecondView.toggle()
}) {
Text("Dismiss")
}
}
}
class SecondViewModel: ObservableObject {
#Published var showSecondView: Bool
//Right here, i'm not sure how to bind 'showSecondView' from FirstView
init(showSecondView: Bool) {
self.showSecondView = showSecondView
}
}

You can pass directly the Binding<Bool> to the second VM but in this way, there's no need to have #Published var and it also doesn't need to be ObservableObject and marked as #ObservedObject. There might be a better solution to this.
struct FirstView: View {
#ObservedObject var vm = FirstViewModel()
var body: some View {
Button(action: {
self.vm.showSecondView.toggle()
}) {
Text("Show second view")
}
.sheet(isPresented: $vm.showSecondView) {
SecondView(vm: SecondViewModel(showSecondView: self.$vm.showSecondView))
}
}
}
class FirstViewModel: ObservableObject {
#Published var showSecondView = false
}
struct SecondView: View {
var vm: SecondViewModel
var body: some View {
Button(action: {
self.vm.showSecondView.wrappedValue.toggle()
}) {
Text("Dismiss")
}
}
}
class SecondViewModel {
var showSecondView: Binding<Bool>
init(showSecondView: Binding<Bool>) {
self.showSecondView = showSecondView
}
}

Related

Refresh List After a New Entity is Added in Core Data for SwiftUI App

I am building a small app using SwiftUI and Core Data. I have a main view, which launches the sheet. The sheet allows me to add a new movie to the SQLite database through Core Data. But I am having a hard time to refresh the parent view once the sheet is dismissed.
ContentView
struct ContentView: View {
#State private var isPresented: Bool = false
#StateObject private var vm = MovieListViewModel()
var body: some View {
NavigationView {
VStack {
List(vm.movies) { movie in
Text(movie.title)
}
}
.navigationTitle("Movies")
.toolbar(content: {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Add Movie") {
isPresented = true
}
}
})
.sheet(isPresented: $isPresented, content: {
AddMovieView()
})
.onAppear {
try? vm.populateMovies()
}.padding()
}
}
}
AddMovieView
struct AddMovieView: View {
#Environment(\.dismiss) private var dismiss
#StateObject private var vm = AddMovieViewModel()
var body: some View {
Form {
TextField("Title", text: $vm.title)
Button("Save") {
do {
try vm.saveMovie()
dismiss()
} catch {
print(error.localizedDescription)
}
}
}
}
}
Do I need to call vm.populateMovies() on the onDismiss function of the sheet from the ContentView?
You can use a #FetchRequest as follows:
struct ContentView: View {
#FetchRequest(sortDescriptors: []) var movies: FetchedResults<Movie>
#State private var isPresented: Bool = false
#StateObject private var vm = MovieListViewModel()
var body: some View {
NavigationView {
VStack {
List(movies) { movie in
Text(movie.title)
}
}
.navigationTitle("Movies")
.toolbar(content: {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Add Movie") {
isPresented = true
}
}
})
.sheet(isPresented: $isPresented, content: {
AddMovieView()
})
.padding()
}
}
}
You won't need a populateMovies() as the FetchRequest result is automatically populated.

How to pass data between ViewModels in SwiftUI

I have this use case where I have a parent view and a child view. Both of the views have their own corresponding ViewModels.
ParentView:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView()) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}
}
ParentViewModel:
class ParentViewModel: ObservableObject {
#Published var newListName: String = ""
func saveList() {
// some logic to save to CoreData, method would be called via a button
// how do I reference "someString" from ChildViewModel in this ViewModel?
}
}
ChildView:
struct ChildView: View {
#StateObject var childViewModel = ChildViewModel()
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
childViewModel.alterData()
}
}
}
}
}
ChildViewModel:
class ChildViewModel: ObservableObject {
#Published var someString: String = ""
func alterData() {
someString = "Toast"
}
}
My question now is, how do I pass the new value of "someString" from ChildViewModel into the ParentViewModel, in order to do some further stuff with it?
I've tried to create a #StateObject var childViewModel = ChildViewModel() reference in the ParentViewModel, but that does obviously not work, as this will create a new instance of the ChildViewModel and therefore not know of the changes made to "someString"
Solution:
As proposed by Josh, I went with the approach to use a single ViewModel instead of two. To achieve this, the ParentView needs a .environmentObject(T) modifier.
ParentView:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView()) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}.environmentObject(parentViewModel)
}
The ChildView then references that environment Object via #EnvironmentObject without an initializer:
struct ChildView: View {
#EnvironmentObject var parentViewModel: ParentViewModel
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
parentViewModel.alterData()
}
}
}
}
}
Most likely you would use a binding for this situation:
struct ChildView: View {
#Binding var name: String
var body: some View {
NavigationView {
List{
Text("Some element")
.onTapGesture {
name = "Altered!"
}
}
}
}
}
And in the parent:
struct ParentView: View {
#StateObject var parentViewModel = ParentViewModel()
var body: some View {
NavigationView {
List {
TextField("Add Name", text: $parentViewModel.newListName)
NavigationLink(destination: ChildView(name: $parentViewModel.newListName)) {
Label("Select Products", systemImage: K.ListIcons.productsNr)
}
}
}
}
Also, I think you can remove the NavigationView view from ChildView. Having it ParentView is enough.

Making a combine passthrough publisher less global

Swift 5, iOS 13
I want to use passthroughSubject publisher; but I my gut tells me its a global variable and as such very poor practice. How can make this global variable less global, while still being usable. Here's some code to show what I talking about.
I know there are a dozen other ways to do this, but I wanted to create some simple code to illustrate the issue.
import SwiftUI
import Combine
let switcher = PassthroughSubject<Void,Never>()
struct SwiftUIViewF: View {
#State var nextPage = false
var body: some View {
VStack {
Text("Switcher")
.onReceive(switcher) { (_) in
self.nextPage.toggle()
}
if nextPage {
Page1ViewF()
} else {
Page2ViewF()
}
}
}
}
struct Page1ViewF: View {
var body: some View {
Text("Page 1")
.onTapGesture {
switcher.send()
}
}
}
struct Page2ViewF: View {
var body: some View {
Text("Page 2")
.onTapGesture {
switcher.send()
}
}
}
struct SwiftUIViewF_Previews: PreviewProvider {
static var previews: some View {
SwiftUIViewF()
}
}
Here is possible solution - to hold it in parent and inject into child views:
struct SwiftUIViewF: View {
let switcher = PassthroughSubject<Void,Never>()
#State var nextPage = false
var body: some View {
VStack {
Text("Switcher")
.onReceive(switcher) { (_) in
self.nextPage.toggle()
}
if nextPage {
Page1ViewF(switcher: switcher)
} else {
Page2ViewF(switcher: switcher)
}
}
}
}
struct Page1ViewF: View {
let switcher: PassthroughSubject<Void,Never>
var body: some View {
Text("Page 1")
.onTapGesture {
self.switcher.send()
}
}
}
struct Page2ViewF: View {
let switcher: PassthroughSubject<Void,Never>
var body: some View {
Text("Page 2")
.onTapGesture {
self.switcher.send()
}
}
}
An example using #EnvironmentObject.
Let SDK take care of observing / passing things for you, rather than setting up yourself.
Especially when your usage is a simple toggle.
import SwiftUI
import Combine
final class EnvState: ObservableObject { #Published var nextPage = false }
struct SwiftUIViewF: View {
#EnvironmentObject var env: EnvState
var body: some View {
VStack {
Text("Switcher")
if env.nextPage {
Page1ViewF()
} else {
Page2ViewF()
}
}
}
}
struct Page1ViewF: View {
#EnvironmentObject var env: EnvState
var body: some View {
Text("Page 1")
.onTapGesture {
env.nextPage.toggle()
}
}
}
struct Page2ViewF: View {
#EnvironmentObject var env: EnvState
var body: some View {
Text("Page 2")
.onTapGesture {
env.nextPage.toggle()
}
}
}
struct SwiftUIViewF_Previews: PreviewProvider {
static var previews: some View {
SwiftUIViewF().environmentObject(EnvState())
}
}

SwiftUI: Using #Binding to dismiss a modal view not working

I'm passing a #State var down a few views, using #Binding on the child views and when I ultimately set the variable to back to false, sometimes my view doesn't dismiss.
It seems like I can run articleDisplayed.toggle() but if I run an additional function above or below, it won't work.
Any idea what's going on here?
Here's my code:
struct HomeView: View {
#EnvironmentObject var state: AppState
#State var articleDisplayed = false
// MARK: - Body
var body: some View {
NavigationView {
ZStack {
List {
ForEach(state.cards, id: \.id) { card in
Button(action: {
self.articleDisplayed = true // I set it to true here
self.state.activeCard = card
}) {
HomeCell(
card: card,
publicationColor: self.state.publication.brandColor
)
}.sheet(isPresented: self.$articleDisplayed) {
SafariQuickTopicView(articleDisplayed: self.$articleDisplayed)
.environmentObject(self.state)
.environment(\.colorScheme, .light)
}
}
}
}
}
}
}
Then in my SafariQuickTopicView:
struct SafariQuickTopicView: View {
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#EnvironmentObject var state: AppState
#Binding var articleDisplayed: Bool
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
// doesn't matter what's in here
}
.navigationBarItems(trailing: passButton)
}
}
private var passButton: some View {
Button(action: self.state.pass {
DispatchQueue.main.async {
// self.state.removeActiveCardFromState()
self.articleDisplayed.toggle() // this will work but adding a second function in here prevents it from working, above or below the toggle.
}
}
}) {
Text("Pass")
}
}
Finally, in my AppState:
func pass(completion: () -> Void) { // need completion?
guard let activeCard = activeCard else { return }
if let index = cards.firstIndex(where: { $0.id == activeCard.id }) {
activeCard.add(comment: "pass")
rejectCurrentCard() // Does an async operation with an external API but we don't care about the result
addRemovedActiveCardToUserDefaults()
completion()
}
}
Move .sheet out of List, it must be one per view hierarchy, so like
List {
ForEach(state.cards, id: \.id) { card in
Button(action: {
self.articleDisplayed = true // I set it to true here
self.state.activeCard = card
}) {
HomeCell(
card: card,
publicationColor: self.state.publication.brandColor
)
}
}
}
.sheet(isPresented: self.$articleDisplayed) {
SafariQuickTopicView(articleDisplayed: self.$articleDisplayed)
.environmentObject(self.state)
.environment(\.colorScheme, .light)
}

objectWillChange do not update view

I have ViewModel which looks like this:
class ItemsListViewModel : ObservableObject{
var response : ItemsListResponse? = nil
var itemsList : [ListItem] = []
var isLoading = true
let objectWillChange = PassthroughSubject<Void, Never>()
func getItems() {
self.isLoading = true
ApiManager.shared.getItems()
.sink(receiveCompletion: {completion in
}, receiveValue: {
self.response = data
self.isLoading = false
self.objectWillChange.send()
})
}
}
When I receive data from network request I use self.objectWillChange.send() to notify view, but view do not react to this.
My views :
ItemsView
struct ItemsView: View {
var body: some View {
VStack{
Text("Some Title")
ItemsListView()
}
}
}
ItemsListView
struct ItemsListView: View {
#ObservedObject var myViewModel = ItemsListViewModel()
var body: some View {
VStack{
Text("\(self.myViewModel.response?.total")
}.onAppear{
self.myViewModel.getItems()
}
}
}
But the interesting thing, that if I use ItemsListView not inside
ItemsView everything works perfectly. How can i solve this problem?
try this ( i simplified just your model to test in playground)
you can copy directly the code in playground and check
struct Model {
var items : [String]
}
class ItemsListViewModel : ObservableObject {
#Published var items : [String] = ["Test 1", "Test2"]
}
let myViewModel = ItemsListViewModel()
struct ItemsView: View {
var body: some View {
VStack{
Text("Some Title")
ItemsListView().environmentObject(myViewModel)
}
}
}
struct ItemsListView: View {
#EnvironmentObject private var model : ItemsListViewModel
var body: some View {
VStack{
Text("\(model.items.count)")
}
}
}
struct ContentView: View {
var body: some View {
ItemsView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(myViewModel)
}
}
Using #Published for properties of ObservableObject does fix your issue. See simplified below demo:
import SwiftUI
import Combine
class ItemsListViewModel : ObservableObject{
#Published var response = ""
var isLoading = true
func getData() {
self.isLoading = true
DispatchQueue.main.async {
Just("test")
.sink(receiveCompletion: {completion in
}, receiveValue: { data in
self.response = data
self.isLoading = false
})
}
}
}
struct ItemsListView: View {
#ObservedObject var myViewModel = ItemsListViewModel()
var body: some View {
VStack{
Text("\(self.myViewModel.response)")
}.onAppear{
self.myViewModel.getData()
}
}
}
struct ItemsView: View {
var body: some View {
VStack{
Text("Some Title")
ItemsListView()
}
}
}
struct TestPublished: View {
var body: some View {
ItemsView()
}
}
struct TestPublished_Previews: PreviewProvider {
static var previews: some View {
TestPublished()
}
}

Resources