When I wrap a VStack inside a ScrollView, it seemingly removes the horizontal padding applied to the VStack causing the contents to go to the display edge as opposed to leaving space between the contents of the VStack and the edge of the display when horizontal padding is applied. I’m unsure why, or how to resolve this, but I’ve left reference images and my code below.
This is what I get when wrapping the VStack in a ScrollView:
This is the code for what I have:
import SwiftUI
struct SignInView: View {
// @Environment(.colorScheme) var colorScheme
@State private var username: String = ""
@State private var password: String = ""
var body: some View {
ScrollView {
VStack {
Rectangle()
.fill(.cyan)
.offset(y: -100)
.frame(width: UIScreen.main.bounds.width, height: 250)
Text("Sign In to \*\*Name\*\*")
.bold()
.font(.system(size: 25))
TextField("Username", text: $username)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.top)
SecureField("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.bottom)
.frame(maxWidth: .infinity)
Button(action: {
print("Sign In pressed, do something")
}) {
Text("Sign In")
.bold()
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.blue)
.cornerRadius(10)
}
HStack {
Button(action: {
print("Sign In w social option")
}) {
Text("Placeholder for Social")
.bold()
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.blue)
}
Button(action: {
print("Sign In w social option 2")
}) {
Text("Placeholder for Social")
.bold()
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.black)
}
}
Spacer()
}
.padding(.horizontal)
}
}
}
2
Answers
I figured it out, partially. If someone could provide more details on why or explain the reasoning, it'd be great, but it had to do with the .frame modifier for the Rectangle. It seems like using
.frame(width: UIScreen.main.bounds.width)
on the Rectangle within the VStack caused some issue. Moving the Rectangle outside of the VStack, but inside the ScrollView fixes it.Remove width from Rectangle(). Since the width is defined as the screen width, adding padding is making the total width bigger than the width of the screen.
Try the following code