Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Last active May 27, 2021 22:10
Show Gist options
  • Save arashkashi/46eadfee21e72f833af0f44ea46096fb to your computer and use it in GitHub Desktop.
Save arashkashi/46eadfee21e72f833af0f44ea46096fb to your computer and use it in GitHub Desktop.
swiftui get height of text and get the top unsafe height with grace
struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize?
static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) {
value = value ?? nextValue()
}
}
struct ReportSize: View {
var base: Text
var callBack: (CGSize?) -> ()
var body: some View {
base
.background(GeometryReader { proxy in
Color.clear.preference(key: SizePreferenceKey.self, value: proxy.size)
}).onPreferenceChange(SizePreferenceKey.self, perform: { size in
self.callBack(size)
})
}
}
extension Text {
func reportSize(_ callBack: @escaping (CGSize?) -> Void) -> some View {
ReportSize(base: self, callBack: callBack)
}
}
struct ReportTopUnsafeHeight: View {
var base: Color
var callback: (CGFloat) -> ()
@State var withEdge: CGFloat? {
didSet {
sendCallback()
}
}
@State var withoutEdge: CGFloat? {
didSet {
sendCallback()
}
}
func sendCallback() {
if let bigger = withEdge, let smaller = withoutEdge {
callback(bigger - smaller)
}
}
var body: some View {
GeometryReader { proxy in
ZStack {
VStack {
Color.clear.overlay(GeometryReader { proxy in
Color.clear.preference(key: SizePreferenceKey.self, value: proxy.size)
}).onPreferenceChange(SizePreferenceKey.self, perform: { value in
self.withEdge = value?.height
})
}.edgesIgnoringSafeArea(.top)
VStack {
Color.clear.overlay(GeometryReader { proxy in
Color.clear.preference(key: SizePreferenceKey.self, value: proxy.size)
}).onPreferenceChange(SizePreferenceKey.self, perform: { value in
self.withoutEdge = value?.height
})
}
}
}
}
}
extension Color {
func reportTopUnsafeHeight(_ callback: @escaping (CGFloat) -> ()) -> some View {
ReportTopUnsafeHeight(base: self, callback: callback)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment