SwiftUI 中 ScrollView 底部对齐中的 VStack

Hek*_*kes 16 ios swift swiftui vstack

目前正在构建一个聊天应用程序,我需要在屏幕底部显示新消息。我还需要将消息对齐到底部。但是,在 ScrollView 中使用 VStack 默认情况下具有顶部对齐。

忙碌的swiftui

    ScrollView {
        VStack(alignment: .leading, spacing: 16) {
            Spacer()
            .frame(minWidth: 0, maxWidth: .infinity, minHeight:0, maxHeight: .infinity, alignment: Alignment.topLeading)
            ForEach(notList, id: \.self) { not in
                NotRow(not: not)
                    
            }
            
        }
        .padding()
        .frame(minWidth: 0, maxWidth: .infinity, minHeight:0, alignment: Alignment.topLeading)
        
    }
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决这个问题?

Ork*_*nov 19

ScrollView不会向其子级(VStack在本例中)建议与建议的高度相同的高度。它只要求最小尺寸。解决方案是使其直接子节点以向其自身提议的最小高度ScrollView进行响应。我们可以通过读取建议的身高GeometryReader并将其设置为孩子的最小身高来实现这一点。

GeometryReader { reader in
    ScrollView {
        VStack {
            /// Spacer() or Color.red will now behave as expected
        }
        .frame(minHeight: reader.size.height)
    }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*nça 5

我认为你缺少 VStack 中的 maxHeight

VStack(alignment: .leading) {
  Spacer().frame(maxWidth: .infinity)
  // content here
}
.frame(maxHeight: .infinity) // <- this
Run Code Online (Sandbox Code Playgroud)


Ant*_*amy 5

回答那个有点晚了,但它可能会帮助别人。您可以使用一个很好的旧双旋转技巧来实现您想要的结果。其他解决方案不起作用,因为滚动视图内的最大大小未定义,因为它取决于其子视图来计算自己的内容大小。

ScrollView {
  VStack(alignment: .leading, spacing: 16) {
      Spacer()
      .frame(minWidth: 0, maxWidth: .infinity, minHeight:0, maxHeight: .infinity, alignment: Alignment.topLeading)
      ForEach(notList, id: \.self) { not in
          NotRow(not: not)
      }

  }
  .padding()
  .rotationEffect(Angle(degrees: 180))
}
.rotationEffect(Angle(degrees: 180))
Run Code Online (Sandbox Code Playgroud)


Ben*_*enj 0

尝试将所有的Alignment.topLeadings 更改为Alignment.bottomLeading