The View protocol lets you create what users see on the screen. The body property defines the content and layout of that view.
0
0
View protocol and body property in iOS Swift
Introduction
When you want to create a screen or part of a screen in a SwiftUI app.
When you need to show text, images, buttons, or other UI elements.
When you want to organize your app's interface into reusable pieces.
When you want to describe how your UI looks and behaves in a simple way.
Syntax
iOS Swift
struct MyView: View {
var body: some View {
// UI elements here
}
}The body property must return exactly one view.
Use some View to tell SwiftUI you return a view without specifying the exact type.
Examples
A simple view showing a text greeting.
iOS Swift
struct GreetingView: View {
var body: some View {
Text("Hello, friend!")
}
}A blue circle with a fixed size.
iOS Swift
struct ColoredCircle: View {
var body: some View {
Circle()
.fill(Color.blue)
.frame(width: 100, height: 100)
}
}A vertical stack with two text views styled differently.
iOS Swift
struct CombinedView: View {
var body: some View {
VStack {
Text("Title")
.font(.largeTitle)
Text("Subtitle")
.foregroundColor(.gray)
}
}
}Sample App
This app shows a welcome message and a button. When you tap the button, it prints a message in the console.
iOS Swift
import SwiftUI struct ContentView: View { var body: some View { VStack(spacing: 20) { Text("Welcome to SwiftUI!") .font(.title) .padding() Button("Tap me") { print("Button tapped") } .buttonStyle(.borderedProminent) } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
OutputSuccess
Important Notes
The body property is recomputed when state changes, so keep it fast and simple.
Every SwiftUI view must conform to the View protocol and implement body.
You can combine many views inside body using containers like VStack, HStack, and ZStack.
Summary
The View protocol defines what your UI shows.
The body property returns the view's content and layout.
Use simple SwiftUI views inside body to build your interface.