How to Add HStack in iOS SwiftUI

SwiftUI brings a declarative way to build UIs for Apple platforms, and understanding it is crucial for modern iOS development. One of the basic, yet powerful SwiftUI views is the HStack. Let’s take a deep dive into it.

What is SwiftUI HStack?

HStack in SwiftUI stands for Horizontal Stack. It’s a view that arranges its child views in a horizontal line. By using HStack, you can place multiple views side by side horizontally.

HStack in SwiftUI

In SwiftUI, using HStack is straightforward. Here is how you can create a simple HStack.

HStack {

In the example above, “Hello” and “World” will be displayed horizontally on the screen.

swiftui hstack

Modify HStack Spacing

One of the great features of HStack is the ability to modify the spacing between the child views. This can be done by passing a value to the initializer.

HStack(spacing: 20) {

In this instance, the “Hello” and “World” texts will have 20 points spacing between them.

Align Views in HStack

HStack provides alignment options. If your views are of different sizes, alignment is a way to specify how those views should line up.

HStack(alignment: .bottom) {

In the example above, the texts “Hello” and “World” will be bottom-aligned, despite “World” having a larger font size.

swiftui hstack alignment

SwiftUI’s HStack is a core building block for your apps’ user interfaces. Its simplicity makes it a versatile tool in arranging views horizontally. By mastering HStack, you’re well on your way to creating stunning and flexible UIs for your SwiftUI applications.

Similar Posts

Leave a Reply