How to Create a View in SwiftUI: Simple Guide
In SwiftUI, you create a view by defining a struct that conforms to the
View protocol and implementing the body property to describe the UI. Use built-in views like Text, Image, and layout containers inside the body to build your interface.Syntax
To create a view in SwiftUI, define a struct that conforms to the View protocol. Inside, implement the var body: some View property which returns the UI elements composing the view.
- struct: Defines a new view type.
- View: Protocol that your struct must conform to.
- body: A computed property that returns the UI layout.
swift
struct MyView: View {
var body: some View {
Text("Hello, SwiftUI!")
}
}Output
A screen showing the text: Hello, SwiftUI!
Example
This example shows a simple SwiftUI view displaying a greeting message centered on the screen with some padding and a blue background.
swift
import SwiftUI struct ContentView: View { var body: some View { Text("Welcome to SwiftUI") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Output
A centered text "Welcome to SwiftUI" with white letters on a blue rounded rectangle background.
Common Pitfalls
Common mistakes when creating views in SwiftUI include:
- Not conforming to the
Viewprotocol. - Forgetting to implement the
bodyproperty. - Trying to use UIKit views directly without wrappers.
- Using mutable state incorrectly inside views.
Always keep views as simple, declarative descriptions of UI.
swift
/* Wrong: Missing View conformance and body */ struct BadView { var text = "Hello" } /* Right: Conforms to View and implements body */ struct GoodView: View { var body: some View { Text("Hello") } }
Quick Reference
Here is a quick summary of creating views in SwiftUI:
| Concept | Description |
|---|---|
| struct MyView: View | Defines a new SwiftUI view |
| var body: some View | Required property describing the UI |
| Text("Hello") | Basic text view |
| Modifiers | Methods like .padding(), .background() to style views |
| PreviewProvider | Enables live preview in Xcode |
Key Takeaways
Create a SwiftUI view by defining a struct that conforms to the View protocol.
Implement the body property to describe the UI using built-in views and modifiers.
Keep views simple and declarative without mutable state inside the view struct.
Use PreviewProvider to see live previews of your views in Xcode.
Avoid UIKit views directly; use SwiftUI components or wrappers instead.