0
0
iOS Swiftmobile~20 mins

Spacer and padding in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Spacer and Padding Demo
This screen shows how to use Spacer and padding to arrange two buttons horizontally with space between them and padding around.
Target UI
+----------------------------------+
|                                  |
|  [Button 1]        [Button 2]    |
|                                  |
+----------------------------------+
Place two buttons side by side horizontally
Add a Spacer between the buttons to push them apart
Add padding around the buttons and the edges of the screen
Use SwiftUI layout components
Starter Code
iOS Swift
import SwiftUI

struct SpacerPaddingDemoView: View {
    var body: some View {
        HStack {
            // TODO: Add Button 1 here
            // TODO: Add Spacer here
            // TODO: Add Button 2 here
        }
        // TODO: Add padding around HStack
    }
}

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

struct SpacerPaddingDemoView: View {
    var body: some View {
        HStack {
            Button("Button 1") {
                // Action for Button 1
            }
            Spacer()
            Button("Button 2") {
                // Action for Button 2
            }
        }
        .padding()
    }
}

struct SpacerPaddingDemoView_Previews: PreviewProvider {
    static var previews: some View {
        SpacerPaddingDemoView()
    }
}

We use an HStack to place the two buttons horizontally. The Spacer() between them pushes them apart, creating space. The .padding() modifier adds space around the entire horizontal stack, so the buttons are not touching the screen edges. This layout is simple and uses SwiftUI's built-in components to manage spacing and padding effectively.

Final Result
Completed Screen
+----------------------------------+
|                                  |
|  [Button 1]        [Button 2]    |
|                                  |
+----------------------------------+
Tapping 'Button 1' triggers its action (currently empty).
Tapping 'Button 2' triggers its action (currently empty).
Buttons are spaced apart with flexible space between them.
Padding keeps buttons away from screen edges.
Stretch Goal
Add background color and rounded corners to the buttons
💡 Hint
Use the .background() modifier with Color and .cornerRadius() on each Button