firstly I am really new to iOS development and Swift (2 weeks coming here from PHP :))
I am building my simple Login page and wondering how to make my Logo image at the top of the page. Also I am wondering if I have done my layout wrong to get the desired layout as in the screenshot. Would appreciate the help on this.
(Logo scribbled out in the screen shot needs to go to the top outside the white background)
Thanks
LoginView:
import SwiftUI
struct LoginView: View {
@State private var email: String = ""
@State private var password: String = ""
let verticalPaddingForForm = 40
var body: some View {
ZStack {
Color(red: 20/225.0 ,green: 22/225.0 , blue: 25/225.0)
VStack(spacing: CGFloat(verticalPaddingForForm)) {
Image("logo")
.resizable()
.scaledToFit()
Divider()
VStack {
TextField("Email", text: $email)
.padding(.horizontal, 30).padding(.top, 20)
Divider()
.padding(.horizontal, 30)
SecureField("Password", text: $password)
.padding(.horizontal, 30).padding(.top, 20)
Divider()
.padding(.horizontal, 30)
}
.background(Color(.white))
Text("Forgotten Password")
.foregroundColor(.blue)
.font(.system(size: 15))
Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
Text("Login")
.padding()
.font(.system(size: 20))
}
.background(Color.black)
.foregroundColor(Color.white)
.cornerRadius(10)
.padding(.top, 0)
.padding(.bottom, 20)
}
.padding(.horizontal, CGFloat(verticalPaddingForForm))
.background(Color(.white))
VStack{
Spacer()
Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
Text("Register")
.padding()
.font(.system(size: 40))
}
.background(Color(red: 20/225.0 ,green: 22/225.0 , blue: 25/225.0))
.foregroundColor(Color.white)
.cornerRadius(10)
.padding()
}
}.ignoresSafeArea()
};
}
ContentView:
import SwiftUI
struct ContentView: View {
var body: some View {
LoginView()
}
}
extension UIDevice {
var hasNotch: Bool {
let bottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
return bottom > 0
}
}
3
Answers
Try below code-:
Use a
ZStack
to give abackgroundColor
to your view, and give that a modifier of.ignoresSafeArea()
.Use
VStack
insideZStack
to layout other view components. I have done few modifications on my side.You can use
ZStack (alignment: .top)
to set the alignment from the top. And then you can use aSpacer()
at the end of the secondVStack
to expand the view.The following code works for me. It’s your code with little changes. Also, I suggest you create a subview to better organize your code, instead of writing all views within the same view.
Just put
Spacer()
betweenImage("logo")
andDivider()
to push your logo to the top of the screen