Created
March 9, 2020 16:49
-
-
Save ryanashcraft/1f4411c0506e936112d6e6d3898f7ba1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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