Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created March 29, 2022 04:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chriseidhof/26151294fbceeca21eb1f857372cfd0f to your computer and use it in GitHub Desktop.
Save chriseidhof/26151294fbceeca21eb1f857372cfd0f to your computer and use it in GitHub Desktop.
import SwiftUI
struct MySample: _ArchivableView {
var body: some View {
Rectangle()
}
func sizeThatFits(in proposedSize: _ProposedSize) -> CGSize {
print(proposedSize.pretty)
return proposedSize.orDefault
}
}
struct ContentView: View {
var body: some View {
MySample()
.aspectRatio(100/50, contentMode: .fill)
.frame(width: 320, height: 480)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// Helpers
extension CGFloat {
var pretty: String {
if self == .infinity {
return ".inf"
} else {
return String(format: "%.1f", self)
}
}
}
extension Optional where Wrapped == CGFloat {
var pretty: String {
self?.pretty ?? "nil"
}
}
extension CGSize {
var pretty: String {
"\(width.pretty)⨉\(height.pretty)"
}
}
extension SwiftUI._ProposedSize {
var orDefault: CGSize {
CGSize(width: _width ?? 10, height: _height ?? 10)
}
var _width: CGFloat? {
Mirror(reflecting: self).children.first { $0.label == "width"}?.value as? CGFloat
}
var _height: CGFloat? {
Mirror(reflecting: self).children.first { $0.label == "height"}?.value as? CGFloat
}
var pretty: String {
return "\(_width.pretty)⨉\(_height.pretty)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment