SwiftUI在VStack/HStack中重复绘制边框

3

我在HStack和VStack中有许多瓷砖视图。每个瓷砖视图都应该有一个边框。我面临的问题是,我不想在我的Stack中有任何间距。然而,这会导致相邻的视图出现重复的边框。

这是我的例子:

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

底部边框宽度为1.0。但是,每当有相邻的元素时,边框宽度将变为2.0。有没有解决方法?我需要仅在特定边缘设置边框,以避免重叠。但在SwiftUI中默认情况下不可能实现。
2个回答

3
让我们倒过来思考一下...并使用类似以下的东西。
已测试通过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
又一次干得好,Asperi!谢谢。我其实发现间距为-1也可以,但你的看起来更好。 - davidev

1
你可以使用spacing: -1.0(或者您的边框宽度) :)
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)
    }
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接