This repository contains custom Swift macros for use with the InjectionIII tool, allowing you to preview and inject SwiftUI views, UIViews, and UIViewControllers into a running application without needing to restart the app.
- SwiftUI View Previews: Use the
InjectPreviewmacro to display a SwiftUI view in a running application. - UIKit Previews: Previews for
UIViewandUIViewControllerobjects can be injected similarly, streamlining UIKit-based UI development. - AppKit Previews: Previews for
NSViewandNSViewControllerobjects can be injected similarly, streamlining AppKit-based UI development. - Debug Mode Only: These macros are available only in DEBUG builds, ensuring they do not affect production performance.
For SwiftUI views, the InjectPreview macro can be used like this:
import SwiftUI
#InjectPreview {
Text("Hello, World!")
}This will inject the view into a running application and also show it in the Xcode canvas, enabling real-time updates.
Tip
You can use SwiftUI property wrappers like @State or @Environment inside the InjectPreview macro.
For UIView/NSView or UIViewController/NSViewController, similar macros are available. Example usage:
#InjectPreview {
let label = UILabel()
label.text = "Hello, UIView!"
return label
}To make this preview work with the Xcode canvas, wrap the body of this macro in a PreviewProvider type:
enum Previews: PreviewProvider {
#InjectPreview {
let text = NSText()
text.string = "Hello, World!"
return text
}
}- Swift 5.9+
- InjectionIII tool (latest version)
- These macros are limited to DEBUG builds only.
Add this repository to your project and ensure that the InjectionIII tool is set up and running during development. The @InjectPreview macros can be used immediately in your codebase following the examples above.
Create a Package.swift file.
// swift-tools-version:5.7
import PackageDescription
let package = Package(
name: "SomeProject",
dependencies: [
.package(url: "https://github.com/dankinsoid/swift-inject-preview.git", from: "1.3.0")
],
targets: [
.target(
name: "SomeProject",
dependencies: [
.product(name: "SwiftInjectPreview", package: "swift-inject-preview"),
]
)
]
)@_exported import SwiftInjectPreviewNote
This macro does not add InjectionIII to your target. It is recommended to use HotReloading or other similar packages, or add InjectionIII to your project manually.
dankinsoid, [email protected]
SwiftInjectPreview is available under the MIT license. See the LICENSE file for more info.