Reputation: 431
Below is my code to make a View in SwiftUI. I want to position my Welcome button to the bottom of the screen as shown below.
struct welcomeViewControllerView: View {
var body: some View {
Text("Welcome")
.font(.system(size: 20, design: .rounded))
.padding(.leading)
.multilineTextAlignment(.center)
.background(
Image("splashBackground")
.resizable()
.edgesIgnoringSafeArea(.all)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
Button(action:{print("button pressed")})
{
Text("Continue")
.font(.system(size: 20, design: .rounded))
.foregroundColor(.black)
.frame(width: 300, height: 50, alignment: .center)
.background((Image("buttonImage")).resizable().frame(width: 300, height: 50, alignment: .center))
}
}
}
class welcomeViewController: UIHostingController<welcomeViewControllerView> {
required init?(coder: NSCoder)
{
super.init(coder: coder,rootView: welcomeViewControllerView());
}
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = .white
}
}
How can I position my button to the bottom of the screen? I posted the screen below. I am fairly new to using SwiftUI.
Upvotes: 13
Views: 39893
Reputation: 157
use safeAreaInset.
VStack() {
}.safeAreaInset(edge: VerticalEdge.bottom) {
Text("Sticky Button")
}
Upvotes: 5
Reputation: 1472
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "heart.fill")
.resizable()
.frame(width: 60, height: 60)
.foregroundColor(.red)
Group{
Text("Welcome!")
.font(.title)
Button(action: {
print("tapped!")
}, label: {
Text("Continue")
.foregroundColor(.white)
.frame(width: 200, height: 40)
.background(Color.green)
.cornerRadius(15)
.padding()
})
}.frame(maxHeight: .infinity, alignment: .bottom)
}
}
}
Result:
Upvotes: 25
Reputation: 297
Your question included a background image, the code below uses ZStack and Spacer to get the layout with a background underneath. Spacer is definitely your friend to push content horizontally or vertically.
For the background, because it is mostly black, I used Color.black to paint the entire screen and assume you could use a smaller image for the logo. This lets you ship a way smaller image which won't distort. Separating the screen color also lets you match the device light/dark mode settings. See Color(UIColor.systemBackground) and @Environment(.colorScheme) if interested.
ZStack {
Color.black
Text("Welcome")
.foregroundColor(.white)
.font(.title)
VStack {
Image(systemName:"flame.fill")
.resizable()
.aspectRatio(contentMode:.fit)
.foregroundColor(Color.blue)
.frame(height:100)
.padding([.top], 20)
Spacer() // will spread content to top and bottom of VStack
Button(action:{print("Continue")}){
Text("Continue")
.foregroundColor(.black)
.padding(10)
.background(Color.green)
.cornerRadius(10)
}
Spacer()
.frame(height:50) // limit spacer size by applying a frame
}
}
Above gets you below: Layout with bkg using ZStack and Spacer
Upvotes: 8