在 SwiftUI 中使 VStack 填充屏幕的宽度 [英] Make a VStack fill the width of the screen in SwiftUI

查看:24
本文介绍了在 SwiftUI 中使 VStack 填充屏幕的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(alignment: .leading) {
      Text("Title")
        .font(.title)

      Text("Content")
        .lineLimit(nil)
        .font(.body)

      Spacer()
    }
    .background(Color.red)
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
#endif


结果是这个界面:


It results in this interface:

即使标签/文本组件不需要全宽,如何让 VStack 填充屏幕的宽度?

How can I make the VStack fill the width of the screen even if the labels/text components don't need the full width?

我发现的一个技巧是在结构中插入一个 empty HStack ,如下所示:

A trick I've found is to insert an empty HStack in the structure like so:

VStack(alignment: .leading) {
  HStack {
    Spacer()
  }
  Text("Title")
    .font(.title)

  Text("Content")
    .lineLimit(nil)
    .font(.body)

  Spacer()
}

产生所需的设计:

有更好的方法吗?

推荐答案

尝试使用带有以下选项的 .frame 修饰符:

Try using the .frame modifier with the following options:

.frame(
      minWidth: 0,
      maxWidth: .infinity,
      minHeight: 0,
      maxHeight: .infinity,
      alignment: .topLeading
    )

struct ContentView: View {
  var body: some View {
    VStack(alignment: .leading) {
      Text("Hello World")
        .font(.title)
      Text("Another")
        .font(.body)
      Spacer()
    }
    .frame(
      minWidth: 0,
      maxWidth: .infinity,
      minHeight: 0,
      maxHeight: .infinity,
      alignment: .topLeading
    )
    .background(Color.red)
  }
}

这被描述为一个灵活的框架(参见文档),它将延伸到填满整个屏幕,当它有多余的空间时,它会将其内容居中.

This is described as being a flexible frame (see the documentation), which will stretch to fill the whole screen, and when it has extra space it will center its contents inside of it.

这篇关于在 SwiftUI 中使 VStack 填充屏幕的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆