-
Notifications
You must be signed in to change notification settings - Fork 48
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) {} | ||
} |