Home > Enterprise >  Showing Overlay Aligning to the Bottom
Showing Overlay Aligning to the Bottom

Time:12-31

I want to lay a View over another when I tap a button. The following is my code.

import SwiftUI

struct SheetView: View {
    @State private var showSheet: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                ZStack {
                    Rectangle()
                        .fill(Color.orange)
                        .frame(height: 32.0)
                    Button("Please select a mailing address") {
                        showSheet.toggle()
                    }.foregroundColor(Color.black)
                }
                Spacer()
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationViewStyle(StackNavigationViewStyle())
        }
        .overlay(popOver)
    }
    
    var popOver: some View {
        Group {
            if showSheet {
                ZStack {
                    Color.black.opacity(0.4).ignoresSafeArea()
                    ZStack {
                        Rectangle()
                            .fill(Color.white)
                            //.frame(width: UIScreen.main.bounds.width, height: 400)
                            .frame(maxWidth: .infinity, maxHeight: 320.0, alignment: .bottom)
                            //.position(x: UIScreen.main.bounds.width / 2.0, y: 600)
                    }
                }.onTapGesture {
                    showSheet.toggle()
                }
            }
        }
    }
}

And it looks like the following picture. I get pretty much what I need except that the overlaid View will appear at the center. How can I make it appear, aligning to the bottom View? Thanks.

CodePudding user response:

Here is a fix - use alignment for internal ZStack (tested with Xcode 13.2 / iOS 15.2):

    ZStack(alignment: .bottom) {
        Color.black.opacity(0.4).ignoresSafeArea()
        ZStack {
            Rectangle()
                .fill(Color.white)
                .frame(maxWidth: .infinity, maxHeight: 320.0, alignment: .bottom)
        }
    }
    //.ignoresSafeArea()     // << probably you also need this
    .onTapGesture {
        showSheet.toggle()
    }
  • Related