Created
November 12, 2023 09:07
-
-
Save dral3x/a4d5921922bcba0f98a32dcd80e70aa5 to your computer and use it in GitHub Desktop.
Debug SwiftUI view frames
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 | |
extension View { | |
func frameGeometry(_ color: Color = .red) -> some View { | |
modifier(FrameGeometry(color: color)) | |
} | |
} | |
private struct FrameGeometry: ViewModifier { | |
let color: Color | |
func body(content: Content) -> some View { | |
content | |
.overlay(GeometryReader(content: overlay(for:))) | |
} | |
func overlay(for geometry: GeometryProxy) -> some View { | |
ZStack( | |
alignment: Alignment(horizontal: .trailing, vertical: .top) | |
) { | |
Rectangle() | |
.strokeBorder(style: StrokeStyle(lineWidth: 1, dash: [5])) | |
.foregroundColor(color) | |
Text(describe(geometry)) | |
.font(.caption2) | |
.foregroundColor(color) | |
.padding(2) | |
} | |
} | |
private func describe(_ geometry: GeometryProxy) -> String { | |
var information: [String] = [] | |
// frame size | |
let size = "\(Int(geometry.size.width))x\(Int(geometry.size.height))" | |
information.append(size) | |
// safe area insets, if not all zero | |
if geometry.safeAreaInsets != EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0 ) { | |
let safeAreaInsets = [ | |
geometry.safeAreaInsets.top, | |
geometry.safeAreaInsets.leading, | |
geometry.safeAreaInsets.trailing, | |
geometry.safeAreaInsets.bottom | |
].map { "\(Int($0))" }.joined(separator: ";") | |
information.append("[\(safeAreaInsets)]") | |
} | |
return information.joined(separator: " ") | |
} | |
} | |
struct FrameGeometry_Previews: PreviewProvider { | |
static var previews: some View { | |
VStack(spacing: 8) { | |
Button("This is a button", action: {}) | |
.padding() | |
.frameGeometry() | |
Text("This is a text") | |
.font(.largeTitle) | |
.frameGeometry(.gray) | |
Rectangle() | |
.foregroundColor(.yellow) | |
.frame(width: 200, height: 100) | |
.frameGeometry(.black) | |
} | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.frameGeometry(.blue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment