Skip to content

Instantly share code, notes, and snippets.

@ryanashcraft
Created March 9, 2020 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanashcraft/1f4411c0506e936112d6e6d3898f7ba1 to your computer and use it in GitHub Desktop.
Save ryanashcraft/1f4411c0506e936112d6e6d3898f7ba1 to your computer and use it in GitHub Desktop.
import SwiftUI
struct WidthPreferenceKey: PreferenceKey {
typealias Value = CGFloat?
static var defaultValue: CGFloat?
static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
if let nextValue = nextValue(), value != nextValue {
value = nextValue
}
}
}
struct WidthGetter: View {
var body: some View {
GeometryReader { geometry in
Rectangle()
.fill(Color.clear)
.preference(
key: WidthPreferenceKey.self,
value: geometry.size.width
)
}
}
}
// Usage
struct ContentView: View {
@State var width: CGFloat?
var body: some View {
List {
HStack {
Rectangle()
.fill(Color.red)
.frame(width: 72, height: 72)
Text("Measured width: \(self.width ?? 0)")
Spacer()
}
.background(WidthGetter())
.onPreferenceChange(WidthPreferenceKey.self) { value in
self.width = value
}
.listRowInsets(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment