MobileEntityLogo.png

Hi.

Welcome to the best online resource for IOS & Android tutorials.

How to create UI templates in SwiftUI

How to create UI templates in SwiftUI

Sometimes we need to reuse a certain Text style multiple times in different Views. Instead of creating a function that does the same thing, or rewriting the same Text attributes why not just create a custom View that holds the custom template that you wish. It is quite simple. All we will do is create a View that holds your style attributes. Lets get started.

Text Element with styling attributes

First we have our template, in this case it is a Text View, however you can place anything you wish such as a Image, or even a HStack with a complicated View. The key here is to have a template that is flexible. In this case I have a text parameter of type String that is a @State which is placed where you put the string in the Text view. Now lets see how we contain our Text View to reuse it in other Views.

Our custom View

Above is how we create our dynamic template View with takes in a text parameter. You can set parameters by placing the @State attribute before the variable declaration. Next since we are using Text we pass in the text variable into the string parameter of Text this way we can specify what text we wish to display when calling our CustomText. You can make this view even more dynamic by doing the following.

Even more dynamic View

As you can see we made even more aspects of our view dynamic. Before we only made the text available to the View consuming CustomText, however now you can set the text, color of the text, color of the shadow, and the font. The only things that are not dynamic are the shadow position, and radius because these attributes are what make the text look the way I want it to. Now lets call our View.

Calling CustomText In another View

Now as you can see it looks just like any other SwiftUI View that you normally call.

How to bring Lottie to SwiftUI

How to bring Lottie to SwiftUI

How to add a UIViewController to your SwiftUI ViewT

How to add a UIViewController to your SwiftUI ViewT

0