MVVM in iOS Swift: Using the SwiftUI view model
by Seven Peaks on Mar 4, 2021 10:22:00 AM
Why is the SwiftUI view model essential for iOS application development today? Let’s dig into all our tips on MVVM in iOS Swift covered by our iOS developers below!
“The usage remains the same but we no longer need to keep the reference.”
A good User Interface is important to turn potential visitors into buyers as it facilitates interactions between the user and business website or application.
In this series of “Swift UI Design“, we will discuss why we need an animation in our application and animations in any front-end application. We will go through the basics of an overview of animation with UI before we go to the more advanced topics with our senior iOS developers, Ton and Andrei, who will be discussing more on the SwiftUI view model.
If we want users to like our apps or software, we should design it to behave like a likeable person: respectful, generous and helpful. – Alan Cooper
We need to give user feedback on what’s happening in the application, such as the scrolling or the loading indicator, we get, plus the feedback on what’s happening.
As usual, we understand that the application is still running, but they must wait, and a good animation will give the application memorable. So, this concept is true not only for iOS application but only for all the other front-end application like a web application or the Android application or Safari application.
Most of the framework, for the front-end framework, has basic patient property, meaning that it’s about the transformation or appearance such as the position, angle, and colours etc.
SwiftUI itself provides a very simple and robust way to implement the animations. So, as you can see some assemble for transformation like translation scale and rotation or basically or background colour changing, just using the one line of code to achieve it.
Go along with the transformation or appearance is the timing function where control for the final state of the object will be rendered on the screen.
We have several basic timing functions like linear or the easy is mean the asset at the beginning of the animation or easier is decelerating the end or easy now, it’s a combination of the easiest or easier, we can also have a spring timing function where it’s contained for several factors or parameters like damping or velocity of friction.
All kinds of animation are with you I will be back by one protocol called animatedly. And the next step we will look at what is animatedly is.
Animatedly is a protocol from the Swift UI framework and its companion is animatedly data and animatedly data is vector arithmetic. So, what is the vector arithmetic is a Benson of additive arithmetic was from the standard library.
So, added the arithmetic will provide you with an object to come conformation object ability to do some preliminary operator like subtract or adding itself and an expansion that original metric will provide multiplications it means for any data type object conformed for vector arithmetic will have the ability to scale in up or down itself.
To demonstrate how the vector arithmetic working, we will investigate the symbol opacity transition.
We had to value from the end to define a range of the animation, and then the range will be scale using the vector arithmetic and scale up and down. And finally, we have the final state to display on the screen.
Even we have the many default information supported by the framework. But in real life for all the real applications, we will have the more complex animation we need to do the custom.
As an s5, we will go through a simple assembly to see how they’re the custom animation should work in the intuitive UI.
We define the animated data depends on the number of H. So now it naturally supports the animatedly because that will either conform for vector arithmetic, as you know before.
In this way, combined with the timing function is we defy the final state of the VISTA. Now it animatedly faculty, I added another picture of the timing or the duration, the animation duration to see you have you to see that animate clearer.
Most of us know about the affine transformation from wherever bigger the Euro, the developer, you familiar with the programming language, or even your student you know it from the high school or from the university.
I have my object was using the dense form effect with the one button to control the animation. It doesn’t conform to the animatedly. So, if you’re our iOS developer, you may know CG affine transform will be animate with the UI kit.
We will go with another protocol called geometry effects. So, what geometry effects either another protocol or UI and the conform animatedly. So, here’s simply we can have the projection transform and via the CG affine transform with the translation value.
We have the simple metric transformation metric like a translation scaling or rotation that combines the transformation. So, in general, we have the final state of the object on the screen is equal to the original state multiplied with the dense formation matrix.
You can do the multiple time translation and then scaling and then rotation and then do scaling again and then do translation again. So, it means rotation and then scaling will be different scaling and then rotation or translation and then the rotation will be the different rotation and then translation.
Here the assemble if you can see the translation then scaling will give you the final state different from the scaling and then translation or some lucky way you will have the translation and then rotation with the final slide completely the same rotation and translation, but the way it goes from the beginning to the end is completely different.
What is brought upon is the protocol is a combination of animatedly and the view motif here so the protocol animatedly.
By combining two terms of protocol, we have the protocol composition. Again, we will go to another symbol assemble, to see the housework with the animatedly moody fear.
Here I will define one as a progress indicator because it is a motif here, and we identified two types of animation one for circular and another for sliding.
I created the whiteboard if you’re a QA person, that motif here is the conform for the animated motif here we go the conform animatedly motif here, so I have to do part one animatedly and another part of view body fear because it progresses.
We get uncontained at an input using the sap depend on the style and we clip it so with the way we can modify for any kind of input, as long as it’s a view in the SwiftUI view model, it can be an image, it can be a text, it can be a colour, it can be the sap or whatever, or your custom view of course.
First, we have the SF su casa choosing the circular animation, we have the image we have a tax we have another rectangle by rectangle we can answer combination with the in the combination with the batter and answer another motor vehicle rotation effect and it worked perfectly.
The X the y or x or y or the skewing, or you want to do some special effects based on the transformation. metric.
And lastly, if you want to implement for a custom animation can be applied for any kind of view, or at least a set of view, or set of object type, think about animatable motif here. So we can find the raw code in the GitHub link.
Let’s talk about property Viper first. We’re going to create a property wrapper than a property wrapper in Swift UI and MVVM in iOS Swift.
So what was property or pro UI is property of our poor were introduced into UI into the pipe for 5.1 is to provide by Apple language and is one of sweet blanket feature and property wrapper as a layer of separation between code that many how a problem.
For the store, and code that the fire property basically, we want to share data to you 34 what we do in the normal way, take the full line of code. First, we need to define the property wrapper keyword on the top.
And second property wrapper must be a property name, value. So what project value is the same as his name, project, project value is protecting value from the property value. So, we’re going to create a property bubble to use project value with the condition like this phone number should have 10 characters and we can check if these two are followed by acid Project fall. See, you can say the property as a pivot like this.
What state is the state is one of poverty that Apple provides us when the state value chain property name body inside our view will be called can that’s mean we should use state only inside view and set it to be private.
Look at it as simple. Binding property rubber lets us declare a value that’s come from elsewhere. Next environment object.
Enrolment object property allows us to create views that can share data. If you create a user that will be shared across many parts of your app. For a simple app setting or user, the setting is great for your object.
We create users setting classes with observable object protocol. To use properties, and we create an instant in-app folder.
Let’s get to the project with MVVM in iOS Swift, what I did start with the environment object here I can use a setting by using properties of an observable object and I create an instance here and pass it to elsewhere by using the environment object.
Second, I will show you the setting views here, user setting every room project setting view shows something here hello dawn. It will show like this.
Under this simple way, there are some issues about performance and memory management, don’t worry, and they’re going to tell us Thank you, you can face some issues that can cost you time to change.
We use this SwiftUI view model in one project in production. I couldn’t tell yet that there is a real go-to way to start your application.
But I will tell you, the way we could achieve it, I want to talk about three topics, mostly it’s about the published object will change and observable object in general, then about navigation link as we use it a lot.
And how to create observed objects with parameters. So first, about the observable objects. In general, an observable object is an object that sends the object will change stream, and your view will get updated.
The difference is that the state object managed by Swift UI, it creates when Swift UI presents the view and is cached so you don’t need to worry about memory management.
When your observable object, change any property that mark is published, what it does it send the object will change. So, in this example, you can see it starts a simple timer every second, and it doesn’t have any published so it’s just normal property.
That would be the first issue that you can face when you start to work on your own architecture. That’s means to make your application performant and avoid memory leaks, or any memory issues, you have to be sure that your body is very lightweight.
So, if you want to do any calculations, that takes any time be aware that it can trigger many times behind the scenes, even if the view will not present it on the screen, it still will get called another issue, if you work in this way, with the observed object, you can see that this image property will also get cold every time you create your view.
If you decide to go this way, I will show some workaround what we found about this, but before we move on, I want to talk about navigation link, because navigation link that what you going to use and that can bring you the same issues.
The first issue that when you create a navigation link, you must specify the destination and this destination is in as of you that’s mean when this body will get called every of these destination views will be created. So, this is child one, child two, child three, and each of them creates a child to view.
And this child view creates a SwiftUI view model. And you can see that when this body gets called All three-child view creates and it recreates view model.
Like in this example, we’ll click lazy view, nothing happens, we’ll go to child one, then we create child, go child to create a child. It’s done by simple creating.
Instead of the child view, we create a lazy view. So, we just create a wrapper, just a simple wrapper. Simple is it just provides the closure to build your project. And when SwiftUI renders it, it creates that view at that time.
So, another solution would just create it as a wrapper for lazy negation links. In this way, again, if I use the default one, all child you will get created at that point.
Another challenge we faced when we want to manage the road in let’s call it deep navigation. When we click next, we just change the binding property to true. And what we want to do so we create this view, we pass property to show the next.
The problem is that the navigation link of one view on one view changes that value back to false every time that link gets disappeared, right. So as soon as we click next, we change this property when we go next, something broke inside.
How we can fix it in a simple way? We just create all our views and manage them inside. So, on the first screen, we create a nested view, one and this is just a very Proper to show our view and navigation link to the next one to the next to next to has the same state property to show the next.
If you have many cases in your application when you have this flow. We’ve created a kind of rotor navigation view that replicates this one and cascade the create this body, so you provide the closures of your view builders, like in this example.
We move this property is presented inside our router navigation view. We create our navigation view, row to negation view. And it provides our that presented property that we pass it to our view that we want to change the property to do the next customer order, so that the first screen of our router navigation view, as soon as we click next, it change this property.
And this property sends to the next closure. So, this is our child to view. And when we click next, it will change this property to show disclosure. Instead, we have our property, some different properties that you would like to change.
The last thing that I want to talk, it’s how to create an observable object with the parameters. First thing, you need to think about caching your object, because as we notice, if you use a state object, the swift UI manages it for you.
The problem is that you cannot access the state object from the init. That’s means, you cannot pass any parameters from the unit. If you would like to use a state object, for example, you have to do something like that, you create your view, with some parameters, we would like to, we cannot create the state object over here, because we created this point.
First, you must use some parameters like that, just to pass it to your view model. If you have many parameters, you must duplicate all of them. It will really change your architecture and the way you work.
Like in this example, I’m just trying to fetch some data, whatever from API from the database, or whatever, when we said the ID, right.
If you would like to use an observed object, your observed observable object doesn’t have an optional anymore. So that brings us to the previous issue when you use navigation link or create it in the least or whatever all your view models will get created every time through the SwiftUI view model.
It will create this new model and then when something changed inside this object when this view model updates, view Call this body when this body get cold every time etomidate is not cached detail view, does not catch detail view is kind of simple.
It has its own view model that we get parameters from outside.
To solve this problem, you can go and try to cache your previous value that somehow doesn’t have details. To do that, we create something called a view model provider.
In case you have a, let’s say table view with 100 different child views. Soon as we type Samson as in change, but we go to our provider and turn on output, we will see that every time we type you see use the cached object. In the previous example, without a provider, you just recreate the object every time.
So, when you work on your own architecture, on swift UI, you can’t really take your knowledge of the UI kit architecture and use it in your project.
Be aware of all these issues and try to build architecture with all this information into account considering.
We still trying to find the best way to implement MVVM in iOS Swift, or whatever architecture we can call in the SwiftUI view model. But it’s it seems that it’s easy to create the views with swift UI much easier than in UI kit.
But it gives a lot of pain when you’re working on the data model. And unless you’re aware of all this stuff that SwiftUI view model does behind the scenes.”