首页 > 解决方案 > 使用 .aspectRatio(contentMode: .fill) 后文本离开屏幕

问题描述

我正在尝试使用 SwiftUI 制作带有背景图像的应用程序。但是,图像与屏幕的纵横比不同,使我.aspectRatio(contentMode: .fill)习惯于用它填满整个屏幕。在我开始添加文本之前,这完全正常。添加文本时,它现在会离开屏幕,而不是像通常应该做的那样换行。

这是我的代码:

struct FeaturesView: View
{
    var body: some View
    {
        ZStack
        {
            Image("background")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.all)
            
            VStack(alignment: .leading)
            {
                Text("Hello this is some sample text that i am writing to show that this text goes off the screen.")
            }
            .foregroundColor(.white)
        }
    }
}

这是预览:

预览

如您所见,文本离开了屏幕。我尝试使用“.frame()”并指定宽度和高度来修复它,但这会导致在其他视图中使用视图时出现问题。我正在使用 Xcode 12 测试版。

我是 Swift 和 SwiftUI 的新手,因此感谢所有帮助:)

标签: swiftxcodeswiftui

解决方案


当然可以,因为图像扩展了容器的框架,即ZStack,比屏幕宽度更宽。

这是一个解决方案 - 使图像在真实背景中过上自己的生活,并且不影响他人。使用 Xcode 12 / iOS 14 测试。

var body: some View
{
    ZStack
    {
        // ... other content
        VStack(alignment: .leading)
        {
            Text("Hello this is some sample text that i am writing to show that this text goes off the screen.")
        }
        .foregroundColor(.white)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(
        Image("background")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .edgesIgnoringSafeArea(.all)
    )
}

推荐阅读