【问题标题】:SwiftUI HStack top alignment doesn't workSwiftUI HStack 顶部对齐不起作用
【发布时间】:2020-08-19 03:45:42
【问题描述】:

我试图将 HStack 中的文本(图片中的Test)对齐到顶部,但 HStack align 不起作用。它仍然在中心。

Picture

这是我的代码:

struct ContentView: View {
    var body: some View {
        VStack {
            HStack(alignment: .top) {
                Text("Test")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .multilineTextAlignment(.leading)
                Spacer()
            }
            .frame(width: 480, height: 160)
            HStack {
                Text(
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Neque volutpat ac tincidunt vitae semper quis lectus nulla at. Metus vulputate eu scelerisque felis imperdiet proin fermentum. Viverra accumsan in nisl nisi scelerisque. Aliquet sagittis id consectetur purus ut faucibus pulvinar elementum."
                )
                .font(.body)
                .foregroundColor(Color.black)
                .multilineTextAlignment(.leading)
                .frame(
                    minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity,
                    alignment: .topLeading
                )
                .padding()
            }
            .frame(width: 480, height: 320)
            .background(Color(.white))
        }
        .frame(width: 480, height: 480)
        .background(
            ZStack {
                Rectangle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [.blue, .red]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .blur(radius: 10)

                VisualEffectView(
                    material: .toolTip,
                    blendingMode: .withinWindow
                )
            }
        )
        .mask(
            RoundedRectangle(cornerRadius: 30)
        )
    }
}

【问题讨论】:

  • 发生这种情况可能有几个原因。如果您删除顶部 HStack 和父 VStack 的框架,您会看到它实际上粘在顶部,这是由于手动间距。您可以删除这些框架以适应内容(并使用填充/边距),或者您可以将 VStack + Spacer 作为父级添加到顶部 HStack 以保持当前框架尺寸。

标签: swift swiftui


【解决方案1】:

您需要在框架中添加对齐方式

        HStack {
            Text("Test")
                .font(.largeTitle)
                .fontWeight(.bold)
                .multilineTextAlignment(.leading)
            Spacer()
        }
        .frame(width: 480, height: 160, alignment: .top)   // << here !!

【讨论】:

  • 很好看..但不知道为什么它在框架中?
猜你喜欢
  • 2020-03-19
  • 1970-01-01
  • 2021-06-07
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2020-06-11
相关资源
最近更新 更多