Skip to content

Include the system notification content height in verticalOffset #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions Sources/SystemNotification/SystemNotification.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ public struct SystemNotification<Content: View>: View {

@State
private var currentId = UUID()


@State
private var contentHeight: CGFloat = 0

public var body: some View {
ZStack(alignment: edge.alignment) {
Color.clear
Expand All @@ -74,8 +77,10 @@ public struct SystemNotification<Content: View>: View {
.gesture(swipeGesture, if: config.isSwipeToDismissEnabled)
#endif
.padding(style.padding)
.reportHeight()
.onChange(of: isActive, perform: handlePresentation)
}
.onPreferenceChange(HeightPreferenceKey.self) { contentHeight = $0 }
}
}

Expand All @@ -92,8 +97,8 @@ private extension SystemNotification {
var verticalOffset: CGFloat {
if isActive { return 0 }
switch edge {
case .top: return -250
case .bottom: return 250
case .top: return -250 - contentHeight
case .bottom: return 250 + contentHeight
}
}

Expand Down Expand Up @@ -301,3 +306,31 @@ private extension SystemNotification {

return MyView()
}

private extension View {
func reportHeight() -> some View {
modifier(HeightPreferenceReporter())
}
}
/// Read the height of the notification content and report its height up through the PreferenceKey system to a
/// parent view.
private struct HeightPreferenceReporter: ViewModifier {
func body(content: Content) -> some View {
content.background(
GeometryReader { geometry in
Color.clear.preference(
key: HeightPreferenceKey.self,
value: geometry.size.height
)
}
)
}
}

private struct HeightPreferenceKey: PreferenceKey {
internal static let defaultValue: CGFloat = 0

internal static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}