DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • HLS Streaming With AVKit and Swift UI for iOS and tvOS
  • Exploring Google's Open Images V7
  • Iptables Basic Commands for Novice

Trending

  • TypeScript: Useful Features
  • Chronicle Services: Low Latency Java Microservices Without Pain
  • Hugging Face Is the New GitHub for LLMs
  • Log Analysis Using grep
  1. DZone
  2. Coding
  3. Frameworks
  4. Animating Inserts and Deletes on UICollectionView with Swift

Animating Inserts and Deletes on UICollectionView with Swift

Simon Gladman user avatar by
Simon Gladman
·
Sep. 25, 14 · Tutorial
Like (0)
Save
Tweet
Share
30.79K Views

Join the DZone community and get the full member experience.

Join For Free
When users added or deleted filters in the first iteration of my Filter Chaining application, the updated array of user defined filters was passed into the FiltersCollectionView instance where is simply invoked reloadData() on its UICollectionView. This worked fine, but there was no transition and the new filter suddenly jumped into view.
It would be better to animate the insert or delete and indicate to the user, through movement, how their collection of filters had changed. How to do this wasn’t immediately obvious and this post describes the technique I’ve used.
Inside the view controller, both the deleteSelectedFilter()  and addNewFilter() methods update its userDefinedFilters array:
// deleteSelectedFilter
        userDefinedFilters = userDefinedFilters.filter({!($0 == previousFilter)})

        // addNewFilter
        userDefinedFilters.insert(newFilter, atIndex: userDefinedFilters.count - 1)
and this, in turn, sets the userDefinedFilters property on the FiltersCollectionView via a didSet observer. When that property changes,FiltersCollectionView’s own didSet observer on userDefinedFilters looks at the new version of the array to see whether an item has been added (i.e. the length of oldValue is less that the new value) or deleted (i.e. the length of oldValue is greater than the new value).
Selecting, adding and deleting items in a UICollectionView uses NSIndexPaths rather than, for example, integer indexes or items. Getting theNSIndexPath for a specific item needs an intermediate step. My application always inserts new filters at the penultimate position in the collection view, so I need to find the NSIndexPath for the last but one cell and invoke insertItemsAtIndexPath(). To do this, I use on of the extensions that UICollectionView provides to NSIndexPath - a new init() method:
init(forItem item: Int, inSection section: Int) -> NSIndexPath

…and the implementation to get the required index path is and insert an item is:

  let insertIndexPath = NSIndexPath(forItem: oldValue.count - 1, inSection: 0)

  uiCollectionView.insertItemsAtIndexPaths([insertIndexPath])

When a user deletes a filter, the application assumes they are deleting the selected filter (a fuller implementation would compare oldValueand userDefinedFilters to figure out what’s been deleted). So, in this case, I need to invoke deleteItemsAtSelectedPaths() for the index paths of the selected items:

let deleteIndexPath = uiCollectionView.indexPathsForSelectedItems()[0] as NSIndexPath

  uiCollectionView.deleteItemsAtIndexPaths([deleteIndexPath])
As well as adding or removing filters, both of these set FilterCollectonView’s selectedFilter property. When a filter is added, the new filter is selected and when a filter is removed, the first filter is selected.
Inside its didSet observer, I scroll the selected cell into view so that if the user selects a cell which is partially off-screen it becomes fully visible. In this case, I want to find the index of the selected cell inside userDefinedFilters, then create an NSIndexPath for that index and finally selectItemAtIndexPath() on the new NSIndexPath. 
To that that, the didSet observer on selectedFilter looks like this:
var selectedFilter : UserDefinedFilter?
    {
        didSet
        {
            var selectedIndex : Int = -1

            for (i: Int, filter: UserDefinedFilter) in enumerate(userDefinedFilters)
            {
                if filter == selectedFilter!
                {
                    selectedIndex = i
                }
            }

            if selectedIndex != -1
            {
                let selectedIndexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
                uiCollectionView.selectItemAtIndexPath(selectedIndexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredHorizontally)
            }

            sendActionsForControlEvents(.ValueChanged)
            refresh()
        }
    }
There we have it: rather than cells jarringly appearing and disappearing, a little work with NSIndexPath and properly using UICollectionView’s own insert and delete support gives a smooth transition.
All of this code is available at my GitHub repository here.


Filter (software) Swift (programming language)

Published at DZone with permission of Simon Gladman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • HLS Streaming With AVKit and Swift UI for iOS and tvOS
  • Exploring Google's Open Images V7
  • Iptables Basic Commands for Novice

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: