Skip to content

Commit

Permalink
add read-size code snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
zntfdr committed Aug 15, 2021
1 parent 293e324 commit 0d764ee
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions SwiftUI-read-a-view-size/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Code snippet from [How to read a view size in SwiftUI][fs].

[fs]: https://fivestars.blog/articles/swiftui-share-layout-information/
33 changes: 33 additions & 0 deletions SwiftUI-read-a-view-size/View+readSize.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Original article here: https://fivestars.blog/articles/swiftui-share-layout-information/

import SwiftUI

/*

Example:

var body: some View {
childView
.readSize { newSize in
print("The new child size is: \(newSize)")
}
}

*/

extension View {
func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}

private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

0 comments on commit 0d764ee

Please sign in to comment.