Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI duplicated border in VStack/HStack

Tags:

swiftui

I am having many tiles View in a HStack and VStack. Every tile should have a border around it. The problem that I am facing is that, I do not want to have any spacing in my Stack. However, that is resulting in duplicated border as the View laying next to each other.

Here is my example:

struct TileMain: View {
    
    var body: some View {

        VStack
        {
            HStack(spacing: 0.0)
            {
                Tile()
                    .border(Color.red, width: 1.0)
                Tile()
                    .border(Color.red, width: 1.0)
                Tile()
                    .border(Color.red, width: 1.0)
            }
            HStack(spacing: 0.0)
            {
                Tile()
                .border(Color.red, width: 1.0)

                Tile()
                    .border(Color.red, width: 1.0)
                
                Tile()
                    .border(Color.red, width: 1.0)
            }
            .padding(.bottom, 15)
        }
    }
}
struct Tile : View
{
    var body: some View
    {
        VStack
        {
            Spacer()
            Text("Test")
            Spacer()
        }.frame(width: 150, height: 150)
    }
}

enter image description here

The border at the bottom has 1.0 width. However, everywhere where there is a neighbor, the border will be 2.0 wide. Is there any work around for that? I would need to set border only at special edges, so I do not get any duplications. But that's not possible my default in SwiftUI.

like image 311
davidev Avatar asked Apr 28 '26 09:04

davidev


1 Answers

Let's get upside-down our mind... and use something like the following

Tested with Xcode 11.4 / macOS 10.15.6

demo

struct TileMain: View {

    var body: some View {

        VStack(spacing: 1)
        {
            HStack(spacing: 1)
            {
                Tile()
                Tile()
                Tile()
            }
            HStack(spacing: 1)
            {
                Tile()
                Tile()
                Tile()
            }
        }
        .padding(1)
        .background(Color.red)
    }
}
struct Tile : View
{
    var body: some View
    {
        VStack
        {
            Spacer()
            Text("Test")
            Spacer()
        }.frame(width: 150, height: 150)
        .background(Color(NSColor.windowBackgroundColor))
    }
}
like image 111
Asperi Avatar answered May 01 '26 02:05

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!