Home > Net >  SwiftUI View is taking exceeding edges
SwiftUI View is taking exceeding edges

Time:03-15

I am learning SwiftUI and was trying to replicate an app. I ran into a problem where the view is taking up space outside the frame as well. It looks like this: screenshot

My code for the view is:

struct LessonsScreen: View {
    var body: some View {
        VStack (alignment: .leading) {
            HStack {
                Image(systemName: "arrow.left")
                    .font(.system(size: 30))
                Spacer()
                Image(systemName: "slider.horizontal.3")
                    .font(.system(size: 30))
            }
            
            Text("A2 - Elementary")
                .font(.system(size: 28, weight: .semibold))
                .padding()
            
            LessonCompletion(lessonNum: 1, text: "How are you?", color: .purple)
            
            Image("discussion")
                .cornerRadius(20)
                .frame(width: UIScreen.main.bounds.width, alignment: .center)
            
            LessonCompletion(lessonNum: 2, text: "Pronunciation", color: .green)
            LessonCompletion(lessonNum: 3, text: "Demonstrative pronouns", color: .red)
            LessonCompletion(lessonNum: 4, text: "Present continuous", color: .yellow)
            
            Button(action: {}, label: {
                Text("Get started")
                    .foregroundColor(.white)
                    .frame(width: UIScreen.main.bounds.width - 150, height: 70, alignment: .center)
                    .background(Color.black)
                    .cornerRadius(10)
                    .frame(width: UIScreen.main.bounds.width, alignment: .center)
                    .padding()
            })
        }
    }
}

Can anyone tell me where I messed up the formatting?

CodePudding user response:

If you like to align the button in center in native SwiftUI way, you can use view modifier Spacer() inside HStack() instead of .frame, like this: (and same with 'discussion' Image)

...
            Button(action: {}, label: {
            HStack{
                Spacer()
                Text("Get started")
                    .foregroundColor(.white)
                    .frame(width: UIScreen.main.bounds.width - 150, height: 70, alignment: .center)
                    .background(Color.black)
                    .cornerRadius(10)
                    .padding()
                Spacer()
            }
        })

...

CodePudding user response:

In your button replace

   .frame(width: UIScreen.main.bounds.width, alignment: .center)

with

   .frame(maxWidth: .infinity, alignment: .center)
  • Related