2
votes

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.

2

2 Answers

1
votes

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))
    }
}
1
votes

You can use spacing: -1.0 (or whatever your border width is) :)

struct TileMain: View {
  var body: some View {
    VStack(spacing: -1.0)
    {
      HStack(spacing: -1.0)
      {
        Tile()
          .border(Color.red, width: 1.0)
        Tile()
          .border(Color.red, width: 1.0)
        Tile()
          .border(Color.red, width: 1.0)
      }
      HStack(spacing: -1.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)
    }
  }

}