SwiftUI: 如何让视图延伸到安全区域之外,并在屏幕顶部和底部之间居中?

huangapple go评论70阅读模式
英文:

SwiftUI: How to let a view extend past safe area and center between screen to and bottom?

问题

我有类似以下的代码:

var body: some View
{
    VStack
    {
        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)

        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)

        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)
    }
}

我的图片具有1:1的宽高比。在iPhone上,这意味着没有足够的垂直空间来容纳它们。

目前,这些图片在垂直方向上被压缩。

如何确保这三个图像都填充屏幕的宽度,中间的图像居中显示,并且顶部和底部的图像延伸超出屏幕的顶部和底部边缘?

英文:

I have code that's similar to:

var body: some View
{
    VStack
    {
        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)

        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)

        Image("someImage")
            .resizable()
            .frame(width: UIScreen.main.bounds.width)
    }
}

My image has a 1:1 aspect ratio. On iPhone this would mean that there's not enough vertical space to fit them.

Currently the images are vertically compressed.

How can I make sure that all three images fill the width of the screen, that the middle image is centered, and that the top and bottom images extend past the top and bottom edges of the screen?

答案1

得分: 1

resizable修饰符将告诉图像填充其父级的空间,而不关心原始纵横比例。
你想要的是强制图像保持其纵横比,同时占用所有可用空间(contentMode: .fill):

Image(systemName: "someImage")
  .resizable()
  .aspectRatio(contentMode: .fill)
  .frame(width: UIScreen.main.bounds.width)

如果你在VStack中放置的项多于屏幕上可见的数量,那么内容将已经超出屏幕(和安全区域)的边界,除非内容明确调整大小以适应其父级。
你可以通过将contentMode更改为.fit来查看此行为。

适应 填充
SwiftUI: 如何让视图延伸到安全区域之外,并在屏幕顶部和底部之间居中? SwiftUI: 如何让视图延伸到安全区域之外,并在屏幕顶部和底部之间居中?
英文:

The resizable modifier will tell the image to fill the space of its parent without caring about the original aspect ratio.
What you want is to force the image to maintain its aspect ratio, while occupying all available space (contentMode: .fill):

Image(systemName: "someImage")
  .resizable()
  .aspectRatio(contentMode: .fill)
  .frame(width: UIScreen.main.bounds.width)

If you place more items in a VStack than is visible on screen, the contents will already extend past the bounds of the screen (and the safe area), unless that content explicitly sizes to fit its parent.
You can see this behaviour by changing contentMode to .fit.

Fit Fill
SwiftUI: 如何让视图延伸到安全区域之外,并在屏幕顶部和底部之间居中? SwiftUI: 如何让视图延伸到安全区域之外,并在屏幕顶部和底部之间居中?

huangapple
  • 本文由 发表于 2023年3月7日 05:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定