使用 .aspectRatio(contentMode: .fill) 后文本会离开屏幕

Son*_*oni 1 xcode swift swiftui

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

\n

这是我的代码:

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

这是预览:

\n

预览

\n

正如您所看到的,文本从屏幕上消失了。我尝试使用 \xc2\xb4.frame()\xc2\xb4 并指定宽度和高度来修复它,但这会在其他视图中使用视图时导致问题。我正在使用 Xcode 12 beta。

\n

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

\n

Asp*_*eri 5

当然可以,因为图像扩展了容器的框架,即 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)
    )
}
Run Code Online (Sandbox Code Playgroud)