Home > other >  SwiftUI-Text overflowing screen
SwiftUI-Text overflowing screen

Time:11-26

I am trying to fit a long piece of text inside the screen but it keeps overflowing. Is there a way to wrap the text?

I tried using alignment to make it center but it still goes off the screen.

import SwiftUI

struct OnboardingPage3: View {
    var body: some View {
        ZStack {
            Color("Onboarding")
                .edgesIgnoringSafeArea(.all)
            VStack {
                Color("Onboarding")
                    .edgesIgnoringSafeArea(.all)
                Image("HomeScreen")
                    .resizable()
                    .frame(width: 300, height: 600)
                    .padding(EdgeInsets(top: 0, leading: 0, bottom: 200, trailing: 0))
                
                Text("This is your home screen where you can see how much progress you have made throughout the day as well as a streaks bar to keep track of how many days straight you have been exercising.")
                    .frame(alignment: .center)
            }
        }
    }
}
struct OnboardingPage3_Previews: PreviewProvider {
    static var previews: some View {
        OnboardingPage3()
    }
}

CodePudding user response:

Your text isn't actually overflowing — it's just being truncated.

Single-line text overflowing with dots at the end

To prevent this you can use the fixedSize(horizontal:vertical:) modifier. I also made some other edits to your code — there's no need to use so many .edgesIgnoringSafeAreas, and ZStacks can have some unexpected side effects with positioning.

struct OnboardingPage3: View {
    var body: some View {
        VStack {
            Image("HomeScreen")
                .resizable()
                .aspectRatio(contentMode: .fit) /// use this to maintain the aspect ratio
                .frame(width: 200) /// now you only need to supply 1 dimension

            Text("This is your home screen where you can see how much progress you have made throughout the day as well as a streaks bar to keep track of how many days straight you have been exercising.")
                .fixedSize(horizontal: false, vertical: true)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(20)
        .background(
            Color.gray
                .edgesIgnoringSafeArea(.all)
        )
    }
}

Result:

Image on top, multiline paragraph on bottom
  • Related