Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Use reusable modifier for reading view size
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenHeaps committed Oct 4, 2023
1 parent 55dee55 commit 82eedbb
Showing 1 changed file with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ struct PortfolioSegmentedControl: View {
Spacer()
}
}
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
.onPreferenceChange(SizePreferenceKey.self) { size in
.readSize { size in
if location == .zero {
let newX = selected == .assets ? geometryProxy.size.width / 4 : geometryProxy.size.width / 4 * 3
location = CGPoint(
Expand Down Expand Up @@ -163,7 +162,20 @@ struct PortfolioSegmentedControl: View {
}
}

// https://www.fivestars.blog/articles/swiftui-share-layout-information/
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

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)
}
}

0 comments on commit 82eedbb

Please sign in to comment.