简体   繁体   中英

SwiftUI View is taking exceeding edges

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: 截屏

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?

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

...

In your button replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM