Skip to content

Instantly share code, notes, and snippets.

@ikesyo
Last active September 15, 2023 17:58
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 ikesyo/6c0336346867fe323932a825abd33f28 to your computer and use it in GitHub Desktop.
Save ikesyo/6c0336346867fe323932a825abd33f28 to your computer and use it in GitHub Desktop.
Header
// https://twitter.com/Kyomesuke/status/1702700847183151125
import SwiftUI
struct BiggerWidthPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat { .zero }
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = max(value, nextValue())
}
}
struct ContentView: View {
@State var buttonWidth: CGFloat?
var body: some View {
HStack {
Button("Cancel Cancel") {}
.fixedSize()
.frame(maxWidth: .infinity, alignment: .leading)
.background {
GeometryReader { proxy in
Color.clear.preference(
key: BiggerWidthPreferenceKey.self,
value: proxy.size.width
)
}
}
.frame(minWidth: buttonWidth)
Text("TitleTitleTitleTitleTitleTitle")
.frame(maxWidth: .infinity)
.layoutPriority(1)
Button("Done") {}
.fixedSize()
.frame(maxWidth: .infinity, alignment: .trailing)
.background {
GeometryReader { proxy in
Color.clear.preference(
key: BiggerWidthPreferenceKey.self,
value: proxy.size.width
)
}
}
.frame(minWidth: buttonWidth)
}
.lineLimit(1)
.onPreferenceChange(BiggerWidthPreferenceKey.self) { width in
buttonWidth = width
}
.background {
Color.red.frame(width: 1, height: 100)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment