1

I know that you can turn an IOS SwiftUI view into an image by following these steps, but this uses UIKit things in the SwiftUI extension which you cannot use in macOS SwiftUI. Does anyone know how to snapshot/screenshot a macOS SwiftUI View?

2
  • 1
    That link is for SwiftUI Aug 30, 2021 at 12:24
  • @loremipsum yes but it includes UIKit things which macOS SwiftUI cannot use
    – WilliamD47
    Aug 30, 2021 at 14:39

1 Answer 1

6

In macOS same approach can be used. NSHostingController is analog of UIHostingController. Also to get it drawn the view should be added to some window:

extension View {
    func snapshot() -> NSImage? {
        let controller = NSHostingController(rootView: self)
        let targetSize = controller.view.intrinsicContentSize
        let contentRect = NSRect(origin: .zero, size: targetSize)
        
        let window = NSWindow(
            contentRect: contentRect,
            styleMask: [.borderless],
            backing: .buffered,
            defer: false
        )
        window.contentView = controller.view
        
        guard
            let bitmapRep = controller.view.bitmapImageRepForCachingDisplay(in: contentRect)
        else { return nil }
        
        controller.view.cacheDisplay(in: contentRect, to: bitmapRep)
        let image = NSImage(size: bitmapRep.size)
        image.addRepresentation(bitmapRep)
        return image
    }
}
2
  • Thank you so much! I've tried so many different code snippets to try to get this to work but this one finally did something. However, I needed to put everything from controller.view.cacheDisplay onward into a DispatchQueue.main.async block and return the result in a completion handler. I also hardcoded the targetSize for now because my view wasn't returning the right intrinsicContentSize, but that's an unrelated issue.
    – Angela
    Nov 4, 2022 at 21:31
  • Okay, it turns out if you set the size of the view explicitly with .frame(...), then not only does intrinsicContentSize work, but you can also call window.contentView?.layout() (without it crashing for lack of defined size) to make it work without using DispatchQueue.main.async.
    – Angela
    Nov 7, 2022 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.