【问题标题】:swiftui spacing is not in line with expectationsswiftui间距不符合预期
【发布时间】:2021-08-29 16:33:08
【问题描述】:

我的代码如下:

import SwiftUI


struct DotView: View {
    var body: some View {
        GeometryReader { geo in
            let width = geo.size.width
            VStack() {
                Circle()
                    .frame(width: width, height: width)
                Spacer()
                Circle()
                    .frame(width: width, height: width)
            }
        }
    }
}

struct TestView: View {
    var body: some View {
        GeometryReader { geo in
            VStack() {
                HStack() {
                    Text("11")
                    DotView()
                        .frame(width: 8, height: 23, alignment: .center)
                    Text("22")
                }
                .font(.system(size: 48))
                .background(Color.gray)
                HStack() {
                    Text("123456789")
                }
                .font(.system(size: 30))
                .background(Color.gray)
            }
            .frame(width: geo.size.width, height: geo.size.height)
            .background(Color.blue)
        }
    }
    
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
            .frame(width: 200, height: 200, alignment: .center)
            .cornerRadius(23.0)
    }
}

视图如下图,“11:22”和“123456789”之间有间距

但是,当我将视图 DotView 评论为以下代码时:

struct TestView: View {
    var body: some View {
        GeometryReader { geo in
            VStack() {
                HStack() {
                    Text("11")
//                    DotView()
//                        .frame(width: 8, height: 23, alignment: .center)
                    Text("22")
                }
                .font(.system(size: 48))
                .background(Color.gray)
                HStack() {
                    Text("123456789")
                }
                .font(.system(size: 30))
                .background(Color.gray)
            }
            .frame(width: geo.size.width, height: geo.size.height)
            .background(Color.blue)
        }
    }
}

间距消失。为什么这个 DotView 会影响间距?

【问题讨论】:

  • 尽量避免使用GeometryReader 这样的简单布局。仅在需要获取宽度/高度时使用它,并使用它来计算其他内容(例如,宽度为总宽度的 70% 的进度条)

标签: swiftui spacing


【解决方案1】:

可以在TestView的VStack中添加“(spacing: 0)”

VStack(间距:0)

【讨论】:

  • 我知道间距 0 可以解决。但是为什么默认间距会导致这种差距呢?
  • @mars VStack 的定义说“间距:相邻子视图之间的距离,如果您希望堆栈为每对子视图选择默认距离,则为 nil”。因此,如果 VStack 中没有提供间距,则输入每个子视图的默认距离(例如 VStack 中的HStack()Text()DotView())。而在这种情况下,当调用一个符合 View 协议的结构体 DotView() 结构体时,会应用默认距离,因此如果要调整每个子视图的间距,则必须在 VStack 中调整间距。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多