Last active
December 11, 2023 04:50
-
-
Save sergenes/538dd76d7b6e247a3b763663cc2ed64b to your computer and use it in GitHub Desktop.
SwiftUI Live Preview Logger
This file contains 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
#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