snapshotView without subviews, or a way to access the subviews

Viewed 337

I have a UIView that has another UIView as a subview, I want to animate these views when the user performs a specific action, I want to do this using the snapshotView method.

The problem is that I am unable to snapshot only the main view without the other one being a part of it, and I can't seem to access the subview either to transform it. So my question is, can I snapshot a UIView, without its subviews, or can I access a subview through a snapshot?

2 Answers

Here is simplified demo of possible approach (hide all subviews before snapshot and show right after done)

extension UIView {
    func snapshotMe() -> UIView? {
        _ = self.subviews.compactMap { $0.isHidden = true }
        defer {
            _ = self.subviews.compactMap { $0.isHidden = false }
        }
        return self.snapshotView(afterScreenUpdates: true)
    }
}

of course if your view subviews might be in already mixed hidden/visible state then in provided above extension you have to filter visible only subview in advance.

Once you snapshot a view, it’s essentially just a flattened image. So as a workaround, you could remove the subview from your view, snapshot the view, put the subview back. Or you can snapshot your subview. Or you could do both.

Related