iOS chaining together animations for scrolling table view - ios

So this is a rather simple problem that I've had a rather hard time fixing. I'm trying to take advantage of table views for displaying a huge list of cells because it is already optimized for cell reuse and saves me time in that regard. I need this list to smoothly scroll at an accurate duration. If I scroll too fast cells are still loading when they show on screen so I'm only scrolling one cell at a time.
The code I'm currently using is modified from here: https://stackoverflow.com/a/17956396. I've changed it to only add a single animation to the array and to never remove it. Instead I have a counter that checks to see if there is another cell before scrolling.
This is working fine, but my issue is that I can't update the animation duration to be faster or slower to keep an accurate pace. Is there a way for me to chain animations in a way that would allow me to dynamically update the duration so as to keep accurate timing?

Related

How to animate UITableView rows when IndexPathsForVisibleRows[0] is moved or removed

I am experimenting with the UITableView, but animations are not occurring as I would expect.
Given a list of cells, I want to delete the top-most cell (the item at IndexPathsForVisibleRows[0]), and have all the rows beneath it, animate upwards into their new position.
However, it appears that any time IndexPathsForVisibleRows[0] (or any invisible cell ABOVE the first visible one for that matter) is touched (moved, deleted, etc), the UITableView refuses to animate the results of the transaction.
I have included 2 gifs to demonstrate the issue.
The first GIF demonstrates the desired behavior. I am removing the cell at IndexPathsForVisibleRows[1] (the second on-screen cell).
Notice how all cells below animate correctly into position.
The second GIF demonstrates what happens when removing the top-most cell (IndexPathsForVisibleRows[0]). Note how all the cells below move immediately into the new position, without animation.
(note: the entire table change is wrapped in a BeginUpdates/EndUpdates block).
Am I missing something which causes the 2 scenarios to behave differently, or I have I just stumbled upon a UITableView bug/limitation?
After much investigation, including several new code projects distilling the UITableView down to the various different factors that could be contributing to this behavior, I have found the simple answer.
Don't use the UITableView
I, like many others, have relied heavily on the UITableView in many applications, due to its simplicity and performance, however, if you really want it to behave in fluid, sensible ways, it just cannot deliver.
There are some inherent bugs in it's behavior which don't appear to bet getting addressed by Apple - and not surprisingly, when there is a much better alternative already in the SDK.
Enter the UICollectionView.
I took all my backend logic for and adapted it to supply a UICollectionView instead (all the work took about half an hour), and lo and behold, everything just worked as originally intended.
So, all my code was correct, the UITableView was just getting in the way.
This is how it now looks. Notice have all deletion scenarios animate correctly, no jankiness.
I'm not the first to have found UITableView lacking:
https://pspdfkit.com/blog/2017/the-case-for-deprecating-uitableview/
Additional benefits to UICollectionView:
customizable layouts
easily customizable cell animations
update transaction does not halt currently running scroll animations (this one is great, if you have a background thread refreshing data, you won't get a sudden 'jerk' when rows get rearranged)

UICollectionView reload every second

My sport app keeps track of who is on and off the field, and for how long. I normally have 20-30 people to swap around, during training time. I have a timer to reload the visible cells of the collection view every second. The whole collection view reload can cost between 120-150ms.
The scrolling performance is good, however, sometimes the tapping to swap players does not respond. I think that is when the collection view is trying to reload the cells.
I can see there might a couple of ways:
Use UITableView, with each row to have 4 different elements.
Use UIScrollView, and preload all elements there. We used to use KKGridView library here, but it is way outdated. That is why we move to UICollectionView after 6-7 years
Have anyone had the same issue, and which way should provide the acceptable level of efficiency but not too complex to implement (to reduce the number of bugs)
Keep the record of the cell's index that need to update, then get the Cell from collection view, call method ask it to update itself, push the view update to the cell class, it wont mess with your collection view tap/drag...
Reload whole collectionView is only needed when whole dataSource change, yours is simply cell-by-cell update as I notice

UITableView Smooth Scrolling Issue Because of "tableView:willDisplayCell: Method"

As it's clear from the title, I have a scrolling performance issue in a table view.
Since I have read nearly every question that is posted online in this regard, and I assume all of you have much more experience with UITableView and its techniques, I won't bother with general stuff, and I just wanna point out some key things in my code that may help you help me spot where I'm doing wrong.
The UI in each cell is very very basic, so rendering each doesn't take considerable time. No shadows, no rounded corners, no extra effect, nothing. Just a few labels and two images, that's all.
The datasource is an NSArray which is already fetched from CoreData. The data of the labels are set from the content of the array, without much calculations or process required.
The height is each cell is a static integer, so the tableView:HeightForRowAtIndexPath: will immediately return the result as fast as possible. No calculations required.
The tableView:CellForRowAtIndexPath: dequeues and reuses cell with reusable identifiers so any re-creation is avoided.
So far everything is perfectly smooth. The issue is where items in Core Data are fetched from a server (Which is extremely fast) as user scrolls down. Data binding is done inside tableView:willDisplayCell:atIndexPath: to prevent tableView:CellForRowAtIndexPath: from becoming slow, as data needs to be loaded just before the cell goes live on the screen. I also fetch new items from server inside this method whenever there're some cells remaining till the last item fetched. So for example when there are totally 50 cells data fetched and put in the CoreData already and this method is called for cell number let's say 40, I request another 50 cell data from server, so that it will be ready whenever user reaches the end of the table.
As I expect this should only be called for the cells that go live on the screen. But putting some NSLogs shows that it is called multiple times until next 200 cells data are fetched (I guess the amount changes depending on device or simulator and the memory available on them and also OS limits). For example, I'm testing on an iPhone 7+, and I start the app and I go the page in which the table is. It fetches first 50 items and only first 4 items are shown on the screen, But I see that tableView:willDisplayCell:atIndexPath: is also called for cell #25, so another 50 is fetched immediately, and then it is called for cell #75, so another 50 is fetched, and this goes on for like first 200-300 cells, and then when fetching is stopped, scrolling is extremely fast and optimized until next 200-300 cells are fetched.
What can I do? Shouldn't tableView:willDisplayCell:atIndexPath: fire whenever a cell is about to be displayed? Where else should I fetch data as user scrolls?
Any ideas or suggestions is REALLY and GREATLY appreciated.

UICollectionView performance - _updateVisibleCellsNow

I'm working on a custom UICollectionViewLayout that displays cells organized by day/week/month.
It is not scrolling smooth, and it looks like the lag is caused by [UICollectionView _updateVisibleCellsNow] being called on each rendering loop.
Performance is OK for < 30 items, but at around 100 or more, its terribly slow. Is this a limitation of UICollectionView and custom layouts, or am I not giving the view enough information to perform correctly?
Source here: https://github.com/oskarhagberg/calendarcollection
Layout: https://github.com/oskarhagberg/calendarcollection/blob/master/CalendarHeatMap/OHCalendarWeekLayout.m
Data source and delegate: https://github.com/oskarhagberg/calendarcollection/blob/master/CalendarHeatMap/OHCalendarView.m
Time Profile:
Update
Maybe its futile? Some testing with a plain UICollectionViewController with a UICollectionViewFlowLayout that is given approximately the same amount of cells/screen results in a similar time profile.
I feel that it should be able to handle ~100 simple opaque cells at a time without the jitter. Am I wrong?
Also don't forget to try to rasterize the layer of the cell:
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
I had 10 fps without that, and boom 55fps with!
I'm not really familiar with GPU and compositing model, so what does it do exactly is not entirely clear to me, but basically it flatten the rendering of all subviews in only one bitmap (instead of one bitmap per subview?).
Anyway I don't know if it has some cons, but it is dramatically faster!
I have been doing considerable investigation of UICollectionView performance. The conclusion is simple. Performance for a large number of cells is poor.
EDIT: Apologies, just re-read your post, the number of cells you have should be OK (see the rest of my comment), so cell complexity may also be a problem.
If your design supports it check:
Each cell is opaque.
Cell content clips to bounds.
Cell coordinate positions do not contain fractional values (e.g. always calculate to be whole pixels)
Try to avoid overlapping cells.
Try to avoid drop shadows.
The reason for this is actually quite simple. Many people don't understand this, but it is worth understanding: UIScrollViews do not employ Core Animation to scroll. My naive belief was that they involved some secret scrolling animation "sauce" and simply requested occasional updates from delegates every now and then to check status. But in fact scroll views are objects which don't directly apply any drawing behaviour at all. All they really are is a class which applies a mathematical function abstracting the coordinate placement of the UIViews they contain, so the Views coordinates are treated as relative to an abstract contentView plane rather than relative to the origin of the containing view. A scroll view will update the position of the abstract scrolling plane in accord with user input (e.g. swiping) and of course there is a physics algorithm as well which gives "momentumn" to the translated coordinate positions.
Now if you were to produce your own collection view layout object, in theory, you could produce one which 100% reverses the mathematical translation applied by the underlying scrollview. This would be interesting but useless, because it would then appear that the cells are not moving at all as you swipe. But I raise this possibility because it illustrates that the collection view layout object working with the collection view object itself does a very similar operation to the underlying scrollview. E.g. it simply provides an opportunity to apply an additional mathematical frame by frame translation of the attributes of the views to be displayed, and in the main this will be a translation simply of position attributes.
It is only when new cells are inserted or deleted moved or reloaded that CoreAnimation is involved at all; most usually by calling:
- (void)performBatchUpdates:(void (^)(void))updates
completion:(void (^)(BOOL finished))completion
UICollectionView requests cell layoutAttributes for each frame of scrolling and each visible view is laid out for each frame. UIView's are rich objects optimised for flexibility more than performance. Every time one is laid out, there are a number of tests the system does to check it's alpha, zIndex, subViews, clipping attributes etc. The list is long. These checks and any resulting changes to the view are being conducted for each collection view item for each frame.
To ensure good performance all frame by frame operations need to be completed within 17ms. [With the number of cells you have, that is simply not going to happen] bracketed this clause because I have re-read your post and I realise I had misread it. With the number of cells you have, there should not be a performance problem. I have personally found with a simplified test with vanilla cells, containing only a single cached image, the limit tested on an iPad 3 is about 784 onscreen cells before performance starts to drop below 50fps.
In practice you will need to keep it less than this.
Personally I'm using my own custom layout object and need higher performance than UICollectionView provides. Unfortunately I didn't run the simple test above until some way down the development path and I realised there are performance problems. I'm so I'm going to be reworking the open source back-port of UICollectionView, PSTCollectionView. I think there is a workaround that can be implemented so, just for general scrolling about, each cell item's layer is written using an operation which circumvents the layout of each UIView cell. This will work for me since I have my own layout object, and I know when layout is required and I have a neat trick that will allow the PSTCollectionView to fall back to its normal mode of operation at this time. I've checked the call sequence and it doesn't appear to be too complex, nor does it appear at all unfeasible. But for sure it is non-trivial and some further tests have to be done before I can confirm it will work.
Some more observations that might be helpful:
I am able to reproduce the problem, using flow layout with around 175 items visible at once: it scrolls smoothly in the simulator but lags like hell on iPhone 5. Made sure they are opaque etc.
What ends up taking the most time seems to be work with a mutable NSDictionary inside _updateVisibleCellsNow. Both copying the dictionary, but also looking up items by key. The keys seems to be UICollectionViewItemKey and the [UICollectionViewItemKey isEqual:] method is the most time consuming method of all. UICollectionViewItemKey contains at least type, identifier and indexPath properties, and the contained property indexPath comparison [NSIndexPath isEqual:] takes the most time.
From that I'm guessing that the hash function of UICollectionViewItemKey might be lacking since isEqual: is called so often during dictionary lookup. Many of the items might be ending up with the same hash (or in the same hash bucket, not sure how NSDictionary works).
For some reason it is faster with all items in 1 section, compared to many sections with 7 items in each. Probably because it spends so much time in NSIndexPath isEqual and that is faster if the row diffs first, or perhaps that UICollectionViewItemKey gets a better hash.
Honestly it feels really weird that UICollectionView does that heavy dictionary work every scroll frame, as mentioned before each frame update needs to be <16ms to avoid lag. I wonder if that many dictionary lookups either is:
Really necessary for general UICollectionView operation
There to support some edge case rarely used and could be turned off for most layouts
Some unoptimized internal code that hasn't been fixed yet
Some mistake from our side
Hopefully we will see some improvement this summer during WWDC, or if someone else here can figure out how to fix it.
Here is Altimac's answer converted to Swift 3:
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
Also, it should be noted that this code goes in your collectionView delegate method for cellForItemAtIndexPath.
One more tip - to see an app's frames per second (FPS), open up Core Animation under Instruments (see screenshot).
The issue isn't the number of cells you're displaying in the collection view total, it's the number of cells that are on screen at once. Since the cell size is very small (22x22), you have 154 cells visible on screen at once. Rendering each of these is what's slowing your interface down. You can prove this by increasing the cell size in your Storyboard and re-running the app.
Unfortunately, there's not much you can do. I'd recommend mitigating the problem by avoiding clipping to bounds and trying not to implement drawRect:, since it's slow.
Big thumbs up to the two answers above!
Here's one additional thing you can try: I've had big improvements in UICollectionView performance by disabling auto layout. While you will have to add some additional code to layout the cell interiors, custom code seems to be tremendously faster than auto layout.
Beside the listed answers (rasterize, auto-layout, etc.), you may also want to check for other reasons that potentially drags down the performance.
In my case, each of my UICollectionViewCell contains another UICollectionView (with about 25 cells each). When each of the cell is loading, I call the inner UICollectionView.reloadData(), which significantly drags down the performance.
Then I put the reloadData inside the main UI queue, the issue is gone:
DispatchQueue.main.async {
self.innerCollectionView.reloadData()
}
Carefully looking into reasons like these might help as well.
In few cases it is due to Auto-layout in UICollectionViewCell. Turn it off (if you can live without it) and scrolling will become butter smooth :)
It's an iOS issue, which they havnt resolved from ages.
If you are implementing a grid layout you can work around this by using a single UICollectionViewCell for each row and add nested UIView's to the cell. I actually subclassed UICollectionViewCell and UICollectionReusableView and overrode the prepareForReuse method to remove all of the subviews. In collectionView:cellForItemAtIndexPath: I add in all of the subviews that originally were cells setting their frame to the x coordinate used in the original implementation, but adjusting it's y coordinate to be inside the cell. Using this method I was able to still use some of the niceties of the UICollectionView such as targetContentOffsetForProposedContentOffset:withScrollingVelocity: to align nicely on the top and left sides of a cell. I went from getting 4-6 FPS to a smooth 60 FPS.
Thought I would quickly give my solution, as I faced a very similar issue - image-based UICollectionView.
In the project I was working in, I was fetching images via network, caching it locally on device, and then re-loading the cached image during scrolling.
My flaw was that I wasn't loading cached images in a background thread.
Once I did put my [UIImage imageWithContentsOfFile:imageLocation]; into a background thread (and then applied it to my imageView via my main thread), my FPS and scrolling was a whole lot better.
If you haven't tried it yet, definitely give a go.

iOS UICollectionView lags with scrolling at start

I use a simple UICollectionView in ma iOS in my project.
The view loads about 100 Cells. The Problem appears even if a let the Cells empty.
After ViewDidLoad the Collection view Appears. When i start Scolling about the first three screen Pages down it lags - even with empty cells!
after that i becomes smooth. I also can get top of the page and try again. Scrolling kepps smooth.
2 reasons that you might also encounter
1. Google analytics
If you set up to count every cell view. It starts fast but then slows down and lags because google analytics writes i/o (maybe some caching) as you scroll too fast.
2. DateTime Parsing
DateFormatter is hard if you setup for every cell. Make sure you have a singleton if possible.

Resources