Created
March 8, 2024 01:11
-
-
Save auramagi/c505b2c4493090e1dc7a4132c08ae0b1 to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
@main | |
struct SwiftUIRemakeConstraintsApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
.windowResizability(.contentSize) | |
} | |
} | |
struct ContentView: View { | |
@State var size: CGSize? | |
var body: some View { | |
ZStack(alignment: .top) { | |
VStack(alignment: .leading, spacing: 20) { | |
HStack(alignment: .top) { | |
Image(nsImage: .init(named: NSImage.cautionName)!) | |
.resizable() | |
.scaledToFit() | |
.frame(width: 64, height: 64) | |
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit") | |
.fixedSize(horizontal: false, vertical: true) | |
.readSize($size) | |
.frame(idealWidth: size?.width, minHeight: size?.height) | |
} | |
HStack { | |
Button { } label: { | |
ZStack { | |
Text("Lots of text here") | |
.fixedSize() | |
Text("Cancel") | |
.hidden() | |
Text("OK") | |
.hidden() | |
} | |
} | |
Spacer(minLength: 12) | |
Button { } label: { | |
ZStack { | |
Text("Lots of text here") | |
.hidden() | |
Text("Cancel") | |
.fixedSize() | |
Text("OK") | |
.hidden() | |
} | |
} | |
Button { } label: { | |
ZStack { | |
Text("Lots of text here") | |
.hidden() | |
Text("Cancel") | |
.hidden() | |
Text("OK") | |
.fixedSize() | |
} | |
} | |
} | |
} | |
.padding() | |
} | |
} | |
} | |
struct SizePreference: PreferenceKey { | |
static let defaultValue: CGSize? = nil | |
static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) { | |
value = nextValue() | |
} | |
} | |
extension View { | |
func readSize(_ size: Binding<CGSize?>) -> some View { | |
background { | |
GeometryReader { proxy in | |
Color.clear | |
.preference(key: SizePreference.self, value: proxy.size) | |
.onPreferenceChange(SizePreference.self) { size.wrappedValue = $0 } | |
} | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment