Created
July 6, 2020 23:45
-
-
Save marcpalmer/6922570c23f67b5433bc80c84e957541 to your computer and use it in GitHub Desktop.
Helper for rendering metrics of SwiftUI views in debugging
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
// Created by Marc Palmer on 13/02/2020. | |
// | |
// Usage: Add .debugMetrics(.yellow) or similar to any view | |
import Foundation | |
import SwiftUI | |
/// Renders the width and height of a view | |
struct DebugMetricsModifier: ViewModifier { | |
let colour: Color | |
fileprivate func capsuleText(_ text: LocalizedStringKey) -> some View { | |
return Text(text) | |
.foregroundColor(.white) | |
.font(.caption) | |
.padding(EdgeInsets(top: 2, leading: 10, bottom: 2, trailing: 10)) | |
.background(Capsule().foregroundColor(colour)) | |
} | |
func body(content: Content) -> some View { | |
return content.overlay( | |
GeometryReader { proxy in | |
ZStack { | |
ZStack { | |
self.capsuleText("\(proxy.size.height, specifier: "%.f")") | |
.background(Rectangle() | |
.foregroundColor(self.colour) | |
.frame(width: 2, height: proxy.size.height)) | |
} | |
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .trailing) | |
ZStack { | |
self.capsuleText("\(proxy.size.width, specifier: "%.f")") | |
.background(Rectangle() | |
.foregroundColor(self.colour) | |
.frame(width: proxy.size.width, height: 2)) | |
} | |
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottom) | |
}.overlay(Rectangle() | |
.stroke(self.colour, | |
style: StrokeStyle(lineWidth: 1, | |
lineCap: .round, | |
lineJoin: .miter, | |
miterLimit: 0, | |
dash: [2, 2], | |
dashPhase: 0))) | |
} | |
) | |
} | |
} | |
extension View { | |
func debugMetrics(_ colour: Color = .red) -> some View { | |
self.modifier(DebugMetricsModifier(colour: colour)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment