Matched geometry effect in SwiftUI is a view modifier for creating transition animations between two views. We create two different views, apply the modifier to both of them with a same identifier and namespace, and removing one and inserting another will create an animation where one view moves to the other view’s position. In other words, the view slides from the removed view’s position to the inserted view’s position. Let’s have a look at a concrete example, where we have two rows of views: rectangles and circles. Tapping on any of the views will remove it from one row and insert it into another row. Since we use matchedGeometryEffect view modifier, the change is animated and one view slides to another row.

The view implementation is straight forward. We have a view which renders two rows with ForEach and each row element is a button what has matchedGeometryEffect view modifier applied to. Model items just have an id and colour which is used for setting the foregroundColor. The view model holds two arrays of items, and select methods just remove one item from one array and insert it in another.
The view model’s implementation is shown below. Since we want to animate changes, we use withAnimation block and inside the block just remove one item and then insert it to another. Item properties use @Published property wrapper and the view model is ObservableObject, then property changes trigger view refresh. As one view is removed and the other view is inserted, then matchedGeometryEffect will trigger a transition animation where the view moves from one position to another with default fade animation.
If this was helpful, please let me know on Mastodon@toomasvahter or Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.