Article by: Manish Methani
Last Updated: September 19, 2021 at 8:04am IST
SwiftUI is a modern, declarative framework for building user interfaces across all Apple platforms. It is designed to be easy to use, yet powerful enough to create complex user interfaces. SwiftUI is built around the concept of views, which are the building blocks of your interface.
Views are the visual elements that make up your interface, such as buttons, labels, text fields, and so on. In SwiftUI, a view is a struct that conforms to the View protocol. Views can be nested to create more complex interfaces, and SwiftUI provides a variety of built-in views for common interface elements.
To create a view, you simply create a struct that conforms to the View protocol. Here is an example of a simple view that displays a label:
struct MyView: View { var body: some View { Text("Hello, World!") } }
This view can be used in your interface like this:
struct ContentView: View { var body: some View { VStack { MyView() } } }
The VStack
is another built-in view that arranges its child views vertically. In this case, it contains just one child view, MyView
.
SwiftUI provides a variety of built-in views for layout and styling, such as HStack
, VStack
, ZStack
, Spacer
, Text
, Button
, and many more. You can also create your own custom views that encapsulate more complex functionality.
You can modify the appearance of views using modifiers. Modifiers are operations that are applied to a view to modify its appearance or behavior. For example, you can apply a background color to a view like this:
struct MyView: View { var body: some View { Text("Hello, World!") .background(Color.blue) } }
This applies a blue background to the Text
view.
A: No, SwiftUI requires iOS 13 or later.
A: Yes, SwiftUI and UIKit can be used together in the same app.
A: Yes, SwiftUI is available on macOS 10.15 or later.
That's it! You now have a basic understanding of how to create views in SwiftUI. With this knowledge, you can start building your own SwiftUI apps.