Skip to content

Instantly share code, notes, and snippets.

@MainasuK
Forked from sergenes/PreviewLogger.swift
Created December 11, 2023 04:50
Show Gist options
  • Save MainasuK/d1449431d6da23e5336a3d8e535433f8 to your computer and use it in GitHub Desktop.
Save MainasuK/d1449431d6da23e5336a3d8e535433f8 to your computer and use it in GitHub Desktop.
SwiftUI Live Preview Logger
#pragma mark - Article: https://sergey-nes.medium.com/enhance-your-swiftui-live-preview-workflow-with-previewlogger-6c768e7362a5
import SwiftUI
#pragma mark - ContentView
struct ContentView: View {
@EnvironmentObject var previewLogger: PreviewLogger
var body: some View {
Button("Print Log") {
previewLogger.log("Button tapped in SwiftUI preview!")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(PreviewLogger.shared)
.previewWrapper()
}
}
#pragma mark - PreviewLogger
struct PreviewWrapper: ViewModifier {
@EnvironmentObject var previewLogger: PreviewLogger
func body(content: Content) -> some View {
VStack {
content
List(previewLogger.logMessages.reversed(), id: \.self) { log in
Text(log)
}
}
}
}
extension View {
func previewWrapper() -> some View {
self.modifier(PreviewWrapper())
.environmentObject(PreviewLogger.shared)
}
}
class PreviewLogger: ObservableObject {
static let shared = PreviewLogger()
@Published private(set) var logMessages: [String] = []
func log(_ message: String) {
logMessages.append(message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment