Search code examples
swiftswiftuipositioningoverlap

How to make a Rectangle() and a DatePicker overlap?


So I'm trying to move the rectangle so that it looks like there's a little point at the bottom of the DatePicker() UI element:

import SwiftUI

struct TimeSelectorView: View {
    @State private var selectedDay: Date = Date()
    var body: some View {
        VStack {
            DatePicker(selection: $selectedDay, in: Date()..., displayedComponents: .date) {
                Text("")
            }.frame(width: UIScreen.main.bounds.width * 0.75)
             .clipped()
             .background(Color.white)
             .cornerRadius(15)
            Rectangle()
            .fill(Color.white)
            .frame(width: 25, height: 25)
            .rotationEffect(Angle(degrees: 45))
            .padding(.bottom, 15)
        }
    }
}

Solution

  • To create overlapping Views you can use a ZStack.

    SwiftUI has a dedicated stack type for creating overlapping content, which is useful if you want to place some text over a picture for example. It’s called ZStack, and it works identically to the other two stack types [HStack, VStack].

    In the below example, the DatePicker will be placed behind the Rectangle:

    ZStack {
        DatePicker(...)
        Rectangle()
    }
    

    You can find more information in this tutorial: How to layer views on top of each other using ZStack?