WrappingHStack
WrappingHStack copied to clipboard
Spacing always applied around conditional views, even when they're missing
If a View is created based on a condition and when the condition is false, the "ghost" View is took into account when creating spacing. For example:
import SwiftUI
import WrappingHStack
struct Test: View {
let condition: Bool
var body: some View {
WrappingHStack {
view("view 1")
if condition {
view("view 2")
}
view("view 3")
view("view 4")
view("view 5")
view("view 6")
}
.border(Color.red.opacity(0.5))
.padding(32)
}
private func view(_ text: String) -> some View {
Text(text)
.padding(8)
.border(Color.black)
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test(condition: false)
}
}
The result is the following (note the double spacing between view 1 and view 3):
There's a workaround in this case, that is applying spacing as trailing padding on each view and setting WrappingHStack.Spacing to .constant(0)
, but it would be nice to have it working naturally, especially since this way the trailing padding adds to the view width. Could it be possible to fix this? Thanks.
Nice find! WrappingHStack
implicitly uses spacing: .constant(8)
and apparently the conditional View is passed as nil
. The problem is that, even though the debugger returns true when checking against nil
, an if with the same conditional will fail. I have no idea why this happens, probably some SwiftUI View magic.
The workaround is to use WrappingHStack(spacing: .constant(0))
and set the padding on the elements directly.
I will look at it again when I have time (got to run to a meeting)