0
0
iOS Swiftmobile~15 mins

View protocol and body property in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Greeting Screen
This screen shows a greeting message using a SwiftUI View that conforms to the View protocol and implements the body property.
Target UI
---------------------
|                   |
|   Hello, Friend!   |
|                   |
---------------------
Create a SwiftUI View struct that conforms to the View protocol.
Implement the required body property returning a Text view.
Display the text 'Hello, Friend!' centered on the screen.
Starter Code
iOS Swift
import SwiftUI

struct GreetingView: View {
    // TODO: Implement the body property here
}

struct GreetingView_Previews: PreviewProvider {
    static var previews: some View {
        GreetingView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct GreetingView: View {
    var body: some View {
        VStack {
            Spacer()
            Text("Hello, Friend!")
                .font(.title)
                .multilineTextAlignment(.center)
            Spacer()
        }
    }
}

struct GreetingView_Previews: PreviewProvider {
    static var previews: some View {
        GreetingView()
    }
}

We created a struct GreetingView that conforms to the View protocol. This requires a body property that returns some View.

Inside body, we used a VStack with Spacer() above and below the Text to center it vertically.

The Text displays the greeting message. We set the font to .title for better visibility and aligned the text to center horizontally.

This simple structure demonstrates how to implement the View protocol and provide the required body property.

Final Result
Completed Screen
---------------------
|                   |
|   Hello, Friend!   |
|                   |
---------------------
The screen shows the greeting text centered vertically and horizontally.
No interactive elements on this screen.
Stretch Goal
Modify the view to change the greeting text color based on a Boolean state variable (e.g., toggle between blue and red).
💡 Hint
Use @State to create a Boolean variable and a Button to toggle it. Change the Text color using a ternary operator inside the body.