Create a custom view with content in SwiftUI
In this tutorial, we will learn how we can make custom views in SwiftUI. Custom Views help us divide our complex screen design into tiny and simple layouts that we can edit and change easily as required without changing the entire design.
Let’s see how we can create our design with small structures in SwiftUI. All we have to do is divide the design and create separate views for different parts of the design.
We will be creating our design using three separate views: topView, middleView, and bottomView.
– topView:
struct topView:View{ var body: some View{ Text("Custom Views") .fontWeight(.bold) .font(.title) .offset(y:10) Text(".~_________________________~.") .padding(.bottom,40) } }
– middleView:
struct middleView:View{ var body: some View{ Image("moonlight") .resizable() .scaledToFit() .border(.teal) .padding(.horizontal,10) } }
- border modifier of SwiftUI is used for giving a border around any SwiftUI view. We can use it with any other UIView as well.
- resizable modifier of SwiftUI is used for changing the size of the image. If we don’t use this modifier we won’t be able to modify the image size. So we must use this modifier before using any other modifiers for modifying the image.
– bottomView:
struct BottomView:View{ var body: some View{ Text(".~ Moonlight Scenery ~.") .foregroundColor(Color.teal) .font(.caption) .fontWeight(.semibold) } }
Assembling all the parts in the main view
Just call all the views in the contentView, the main view of the App. It’s just this simple to create custom views in SwiftUI. Now we can alter any particular part without having to do changes in the overall design.
struct ContentView:View{ var body: some View { topView() middleView() BottomView() } }
Also read: Create Custom alert or popup view in SwiftUI
Leave a Reply