0
0
Ios-swiftHow-ToBeginner ยท 3 min read

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 View protocol.
  • Forgetting to implement the body property.
  • 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:

ConceptDescription
struct MyView: ViewDefines a new SwiftUI view
var body: some ViewRequired property describing the UI
Text("Hello")Basic text view
ModifiersMethods like .padding(), .background() to style views
PreviewProviderEnables 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.