Skip to content

Instantly share code, notes, and snippets.

@defagos
Last active December 13, 2022 16:07
Show Gist options
  • Save defagos/6758155afd58190aa6d4c804f0fad5b3 to your computer and use it in GitHub Desktop.
Save defagos/6758155afd58190aa6d4c804f0fad5b3 to your computer and use it in GitHub Desktop.
Decorate the view with a bordered debugging frame whose attached label displays how many times the view body has been evaluated.
import SwiftUI
import UIKit
private struct BodyCounterView: UIViewRepresentable {
let color: UIColor
private let id = UUID() // Force view updates
func makeUIView(context: Context) -> _BodyCounterView {
let view = _BodyCounterView()
view.color = color
return view
}
func updateUIView(_ uiView: _BodyCounterView, context: Context) {
uiView.count += 1
}
}
private class _BodyCounterView: UIView {
private var label = UILabel()
var color: UIColor = .clear {
didSet {
label.backgroundColor = color
layer.borderColor = color.cgColor
}
}
var count: Int = 0 {
didSet {
label.text = " \(count) "
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configureBorder()
configureLabel()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureBorder() {
layer.borderWidth = 2
}
private func configureLabel() {
label.textColor = .white
addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: topAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
}
public extension View {
/// Decorate the view with a bordered debugging frame whose attached label displays how many times the view
/// body has been evaluated.
/// - Parameters:
/// - color: The frame and label color.
func _debugBodyCounter(color: UIColor = .red) -> some View {
overlay {
BodyCounterView(color: color)
.allowsHitTesting(false)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment