-
-
Save MainasuK/d1449431d6da23e5336a3d8e535433f8 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