1
votes

I am trying to make an app with a background image using SwiftUI. However, the image is not the same aspect ratio as the screen, making me use .aspectRatio(contentMode: .fill) to fill the entire screen with it. This works completely fine until I start adding text. When adding text, it now goes off the screen instead of wrapping like it normally should do.

Here's my code:

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

And this is the preview:

Preview

As you can see, the text goes off the screen. I have tried using ´.frame()´ and specifying a width and height to fix it, but that causes issues when using the view inside other views. I am using the Xcode 12 beta.

I'm new to Swift and SwiftUI, so all help is appreciated :)

2

2 Answers

2
votes

Of course it goes, because image expands frame of container, ie ZStack, wider than screen width.

Here is a solution - make image to live own life in real background and do not affect others. Tested with 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)
    )
}
1
votes

this happen because your ZStack using width that equal to your image, try to wrap your image using VStack and geometryReader .

GeometryReader { geometry in
    ZStack {
        Image() // your image
        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: geometry.size.width)     
}

I'm write this on my windows it might some spelling error