10.1 C
New York
Friday, March 28, 2025

swift – Tips on how to evenly area out Views in a HStack?


I’ve a HStack inside my view that’s presupposed to show View contents, with all of them having areas in between components:

import SwiftUI

struct ContentView: View {
    
    var element_1: some View {
        Circle()
            .body(width: 50, peak: 50)
    }
    
    var element_2: some View {
        Circle()
            .body(width: 50, peak: 50)
    }
    
    var element_3: some View {
        Circle()
            .body(width: 50, peak: 50)
    }
    
    var physique: some View {
        HStack {
            Spacer()
            element_1
            Spacer()
            element_2
            Spacer()
            element_3
            Spacer()
        }
    }
}

which reveals the next:

Nonetheless when there are numerous extra views (element_1, element_2, …, element_7), the HStack turns into bit exhausting to learn since there’s too many Spacer() within the HStack which wants some refactoring:

// Instance of getting 7 component Views, with 8 spacers in:

HStack {
    Spacer()
    element_1
    Spacer()
    element_2
    Spacer()
    element_3
    Spacer()
    element_4
    Spacer()
    element_5
    Spacer()
    element_6
    Spacer()
    element_7
    Spacer()
}

I had tried to implement a customized SpacedHStack to realize the identical output in an effort to cut back the HStack into

SpacedHStack {
    element_1
    element_2
    element_3
    element_4
    element_5
    element_6
    element_7
}

with the next struct:

struct SpacedHStack: View {
    var views: [Content]

    init(@ViewBuilder content material: @escaping () -> Content material) {
        self.views = [content()]
    }

    var physique: some View {
        HStack(spacing: 0) {
            ForEach(views.indices, id: .self) { index in
                views[index]
                if index != views.rely - 1 {
                    Spacer()
                }
            }
        }
    }
}

However the output is just not the identical because the earlier HStack with n+1 spacers with n component Views:

The earlier implementation of n+1 spacers for n components helped to permit the weather to place themselves for any iPad dimensions which a set size HStack(spacing: 30){ ... } wouldn’t work (sadly there is not any such factor as HStack(spacing: Spacer()) { ... }). Nonetheless, this makes the code more durable to learn because of the many Spacer()‘s within the HStack. What might be accomplished within the customized SpacedHStack to get the identical output as beforehand accomplished? Alternatively, is there a sublime answer to refactor the HStack in order that it would not want a customized SpacedHStack struct?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles