Ask Your Question
0

When using `presentationDetents(_:)` on `.sheet` in SwiftUI, why does the height not get updated?

asked 2021-04-08 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-10 09:00:00 +0000

qstack gravatar image

The presentationDetents(_:) modifier in SwiftUI is used to add a pull down "detent" to a modal view, allowing the user to partially dismiss the sheet. This modifier does not directly control the height of the sheet.

Instead, you can use the frame(maxHeight:) modifier to set a maximum height for the sheet. For example:

.sheet(isPresented: $isSheetPresented) {
    MySheetView()
        .frame(maxHeight: 500)
        .presentationDetents([.medium()])
}

In this example, the maximum height of the sheet is set to 500 points. When the detent is used to partially dismiss the sheet, the maximum height will remain the same.

If you want the sheet to dynamically adjust its height based on the contents, you can use a combination of GeometryReader and frame(minHeight:idealHeight:maxHeight:). For example:

.sheet(isPresented: $isSheetPresented) {
    GeometryReader { geometry in
        MySheetView()
            .frame(minHeight: 0, idealHeight: geometry.size.height, maxHeight: geometry.size.height)
            .presentationDetents([.medium()])
    }
}

In this example, the GeometryReader allows us to get the size of the container and use it to set the frame of the sheet. The minHeight is set to 0 to allow for dynamic resizing, idealHeight is set to the height of the container, and maxHeight is set to the same as idealHeight to prevent the sheet from resizing when the detent is used.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-08 11:00:00 +0000

Seen: 11 times

Last updated: Mar 10 '23