ios 在 SwiftUI 中使 VStack 填充屏幕的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56487323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:53:55  来源:igfitidea点击:

Make a VStack fill the width of the screen in SwiftUI

iosswiftxcodeswiftui

提问by ielyamani

Given this code :

鉴于此代码:

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 interace:

它导致这种交互:

preview

预览

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

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

A trick I've found is to insert an emptyHStackin the structure like so:

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

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

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

    Spacer()
}

Which yields the desired design:

这产生了所需的设计:

desired output

期望的输出

Is there a better way?

有没有更好的办法?

回答by svarrall

Try using the .frame modifier with the following options:

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

.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.

这被描述为一个灵活的框架(参见文档),它将拉伸以填充整个屏幕,当它有额外的空间时,它将其内容居中。

回答by Jake

There is a better way!

有一个更好的方法!

To make the VStackfill the width of it's parent you can use a GeometryReaderand set the frame. (.relativeWidth(1.0)should work but apparently doesn't right now)

VStack填充它的父级的宽度,您可以使用 aGeometryReader并设置框架。(.relativeWidth(1.0)应该有效,但现在显然不行)

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text("test")
            }
                .frame(width: geometry.size.width,
                       height: nil,
                       alignment: .topLeading)
        }
    }
}

To make the VStackthe width of the actual screen you can use UIScreen.main.bounds.widthwhen setting the frame instead of using a GeometryReader, but I imagine you likely wanted the width of the parent view.

为了使VStack您可以UIScreen.main.bounds.width在设置框架时使用实际屏幕的宽度而不是使用 a GeometryReader,但我想您可能想要父视图的宽度。

Also, this way has the added benefit of not adding spacing in your VStackwhich might happen (if you have spacing) if you added an HStackwith a Spacer()as it's content to the VStack.

此外,这种方式还有一个额外的好处,那就是不会在您的VStack文件中添加间距(如果您有间距),如果您将HStack带有 aSpacer()作为内容添加到VStack.

UPDATE - THERE IS NOT A BETTER WAY!

更新 - 没有更好的方法!

After checking out the accepted answer, I realized that the accepted answer doesn't actually work! It appears to work at first glance, but if you update the VStackto have a green background you'll notice the VStackis still the same width.

查看接受的答案后,我意识到接受的答案实际上不起作用!乍一看似乎可行,但如果您将 更新VStack为绿色背景,您会注意到VStack它的宽度仍然相同。

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

This is because .frame(...)is actually adding another view to the view hierarchy and that view ends up filling the screen. However, the VStackstill does not.

这是因为.frame(...)实际上是将另一个视图添加到视图层次结构中,并且该视图最终会填满屏幕。然而,VStack仍然没有。

This issue also seems to be the same in my answer as well and can be checked using the same approach as above (putting different background colors before and after the .frame(...). The only way that appears to actually widen the VStackis to use spacers:

这个问题在我的回答中似乎也相同,可以使用与上述相同的方法进行检查(在 之前和之后放置不同的背景颜色.frame(...)。似乎实际加宽的唯一方法VStack是使用间隔符:

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {
            HStack{
                Text("Title")
                    .font(.title)
                Spacer()
            }
            Text("Content")
                .lineLimit(nil)
                .font(.body)
            Spacer()
        }
            .background(Color.green)
    }
}

回答by svarrall

An alternative stacking arrangement which works and is perhaps a bit more intuitive is the following:

一种可行且可能更直观的替代堆叠安排如下:

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)
    }
}

The content can also easily be re-positioned by removing the Spacer()'s if necessary.

Spacer()如有必要,还可以通过删除's轻松地重新定位内容。

adding/removing Spacers to change position

添加/移除垫片以改变位置

回答by thiezn

The simplest way I manage to solve the issue was is by using a ZStack + .edgesIgnoringSafeArea(.all)

我设法解决这个问题的最简单方法是使用 ZStack + .edgesIgnoringSafeArea(.all)

struct TestView : View {

    var body: some View {
        ZStack() {
            Color.yellow.edgesIgnoringSafeArea(.all)
            VStack {
                Text("Hello World")
            }
        }
    }
}

回答by fouad mazouz

use this

用这个

.edgesIgnoringSafeArea(.all)

回答by COVID19

You can do it by using GeometryReader

您可以使用 GeometryReader

GeometryReader

几何阅读器

Code:

代码:

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)
            }
        }
    }
}

Your output like:

您的输出如:

enter image description here

enter image description here

回答by ielyamani

One more alternative is to place one of the subviews inside of an HStackand place a Spacer()after it:

另一种选择是将其中一个子视图放在 an 内HStack并在Spacer()其后放置 a :

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

            HStack {
                Text("Title")
                    .font(.title)
                    .background(Color.yellow)
                Spacer()
            }

            Text("Content")
                .lineLimit(nil)
                .font(.body)
                .background(Color.blue)

            Spacer()
            }

            .background(Color.red)
    }
}

resulting in :

导致 :

HStack inside a VStack

HStack inside a VStack

回答by backslash-f

This is what worked for me (ScrollView(optional) so more content can be added if needed, plus centered content):

这对我有用(ScrollView(可选)因此可以根据需要添加更多内容,以及居中的内容):

import SwiftUI

struct SomeView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(Axis.Set.horizontal) {
                HStack(alignment: .center) {
                    ForEach(0..<8) { _ in
                        Text("")
                    }
                }.frame(width: geometry.size.width, height: 50)
            }
        }
    }
}

// MARK: - Preview

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

Result

结果

centered

centered

回答by Jason

I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.

我知道这对每个人都不起作用,但我认为有趣的是,只需添加一个 Divider 就可以解决这个问题。

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

回答by Confused Vorlon

You can use GeometryReader in a handy extension to fill the parent

您可以在一个方便的扩展中使用 GeometryReader 来填充父级

extension View {
    func fillParent(alignment:Alignment = .center) -> some View {
        return GeometryReader { geometry in
            self
                .frame(width: geometry.size.width,
                       height: geometry.size.height,
                       alignment: alignment)
        }
    }
}

so using the requested example, you get

所以使用请求的例子,你得到

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

            Text("Content")
                .lineLimit(nil)
                .font(.body)
        }
        .fillParent(alignment:.topLeading)
        .background(Color.red)
    }
}

(note the spacer is no longer needed)

(注意不再需要垫片)

enter image description here

enter image description here