I’ve a HStack inside my view that’s alleged 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, top: 50)
}
var element_2: some View {
Circle()
.body(width: 50, top: 50)
}
var element_3: some View {
Circle()
.body(width: 50, top: 50)
}
var physique: some View {
HStack {
Spacer()
element_1
Spacer()
element_2
Spacer()
element_3
Spacer()
}
}
}
which reveals the next:
Nevertheless when there are various extra views (element_1, element_2, …, element_7), the HStack turns into bit arduous 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 as a way to scale 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.depend - 1 {
Spacer()
}
}
}
}
}
However the output isn’t 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()) { ... }
). Nevertheless, this makes the code more durable to learn as a result of many Spacer()
‘s within the HStack. What could possibly be finished within the customized SpacedHStack
to get the identical output as beforehand finished? Alternatively, is there a chic answer to refactor the HStack in order that it does not want a customized SpacedHStack
struct?