给定以下代码:

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

它的结果是这个接口:

我怎样才能使VStack填充屏幕的宽度,即使标签/文本组件不需要全宽度?


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

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

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

  Spacer()
}

产生所需的设计:

有没有更好的办法?


当前回答

另一种可行且可能更直观的堆放方式如下:

struct ContentView: View {
    var body: some View {
        HStack() {
            VStack(alignment: .leading) {
                Text("Hello World")
                    .font(.title)
                Text("Another")
                    .font(.body)
                Spacer()
            }
            Spacer()
        }.background(Color.red)
    }
}

如果需要,还可以通过删除Spacer()来轻松地重新定位内容。

其他回答

另一种可行且可能更直观的堆放方式如下:

struct ContentView: View {
    var body: some View {
        HStack() {
            VStack(alignment: .leading) {
                Text("Hello World")
                    .font(.title)
                Text("Another")
                    .font(.body)
                Spacer()
            }
            Spacer()
        }.background(Color.red)
    }
}

如果需要,还可以通过删除Spacer()来轻松地重新定位内容。

我知道这并不适用于所有人,但我认为有趣的是,只需添加一个分隔器就可以解决这个问题。

struct DividerTest: View {
var body: some View {
    VStack(alignment: .leading) {
        Text("Foo")
        Text("Bar")
        Divider()
    }.background(Color.red)
  }
}

只需添加颜色。清除到VStack的底部,就这么简单:)

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

       Color.clear
     }
     .background(Color.red)
   }
 }

你可以通过使用几何阅读器来实现

GeometryReader

代码:

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
               Text("Turtle Rock").frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading).background(Color.red)
            }
        }
    }
}

你的输出如下:

一个好的解决方案,没有“装置”是被遗忘的ZStack

ZStack(alignment: .top){
    Color.red
    VStack{
        Text("Hello World").font(.title)
        Text("Another").font(.body)
    }
}

结果: