I am trying to scroll a cell at a specific location (.bottom) and after the scroll animation finishes run some code. The problem is that scrollToItem function does not provide a completion handler therefor the only solution is to use the delegate (scrollViewDidEndScrollingAnimation). Using that I have one problem though, if the cell is already at that location .didEndScrollAnim. will never be called.
Is there a way to find if a cell is already at UICollectionView.ScrollPosition.bottom ?
collectionView.scrollToItem(at: indexPath, at: [.bottom,.centeredHorizontally], animated: true)
I want to be able to run a part of code when the cell is at the desired location [.bottom] and also animate the scroll if a scroll is needed.
Yes, you can use scrollViewDidEndDecelerating func and this func will call when scroll view grinds (comes) to a halt.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let secondItemIndex = IndexPath(item: 1, section: 0)
categoryCollectionView.selectItem(at: secondItemIndex, animated: true, scrollPosition: .centeredHorizontally)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let secondItemIndex = IndexPath(item: 2, section: 0)
categoryCollectionView.selectItem(at: secondItemIndex, animated: true, scrollPosition: .centeredHorizontally)
}
// Scroll way doesn't effect this func so you can specify any position as you want
I can think of a way, but it involves calling scrollViewDidScroll repeatedly, which does reduce the performance of the screen.
In the func scrollViewDidScroll:
if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
//reach bottom, here your code
}
I set the animated param to false and use UIView.animate() to detect the animation completion.
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}, completion: { [weak self] _ in
// do something after scroll animation completed
}
)
Related
I'm trying to replicate an animation found on the Apple App Store seen here. The app icons move from left to right continuously like a carousel and I'm trying to produce the same behaviour for a single UIView. Is anyone able to help with this? Really struggling:
Something I tried but it stops and repeats the animation without continuing from left to right.
UIView.animateKeyframes(withDuration: 5, delay: 0, options: .repeat, animations: {
viewOfImageViews.center.x += container.bounds.width +
}, completion: nil)
Here is one way you can archive this effect:
Add a collection view
Set cell width the same width as your superview
Set your collection view scroll direction to horizontal
Now in the code when the collection is loaded you scroll to the first section
DispatchQueue.main.async {
self.collView.scrollToItem(at: IndexPath(item: 0, section: 1), at: .left, animated: true)
}
Now you can add this code below so when animation is done it updates the cells and scroll again
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
colors.append(colors.removeFirst())
collView.reloadData()
DispatchQueue.main.async {
self.collView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: false)
self.collView.scrollToItem(at: IndexPath(item: 0, section: 1), at: .left, animated: true)
}
}
Change colors array to your array name which contains the images
I'm using a collection view, UICollectionView, and it works absolutely great...except that I cannot scroll to any particular item. It seems to always scroll to the "middle" is my best guess. In any case, whatever I send to scrollToItem seems to have no effect on the scrolling. I've put it in various locations throughout my view controller but with no success.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let lastIndex = IndexPath(row: messages.count-1, section: 0)
self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}
UICollection View has bug in iOS 14 with scrollToItem. In iOS 14 it will only work if collection view paging will be desable.
So i got a solution if we have to scroll with both manual and programatically.
Specially for iOS 14 and above
self.collView.isPagingEnabled = false
self.collView.scrollToItem(at: IndexPath(item: scrollingIndex, section: 0), at: .left, animated: true)
self.collView.isPagingEnabled = true
You could try putting the scrolling code in viewDidLayoutSubviews which should get called after all table cells are loaded, which means your messages.count should work. Also, make sure you only have a single section in your collection view.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.scrollToBottom()
}
func scrollToBottom() {
DispatchQueue.main.async {
let lastIndex = IndexPath(item: messages.count-1, section: 0)
self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}
}
Swift 5 / iOS 15
I was facing the same problem, so I tried this one-line code and get it done.
// here we slect the required cell instead of directly scrolling to the item and both work same.
self.collectionView.selectItem(at: IndexPath(row: self.index, section: 0), animated: true, scrollPosition: .left)
This is what worked for me, in case you want paging enabled:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.isPagingEnabled = false
collectionView.scrollToItem(
at: IndexPath(item: 1, section: 0),
at: .centeredVertically,
animated: false
)
collectionView.isPagingEnabled = true
}
I just trying to make a custom animation when i scroll to item programmatically. So when I do not compose my animation and using default by cell do not vanishing, but when i put scrolltoItem func inside UIView.animate func the last cell first vanishing and then scrollToItem animates.
In the second picture in the uppermost collectionView the located before indie game cell firstly disappears and only then collectionView scrolls from indie game cell to the next
Why this behavior takes place? Why when i do not animating it purposefully in my way, and just calling scrollToItem with animated = true func, nothing eliminates? if someone do know what happens with the cells, please give me a clue.
UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: {
self.appsCollectionView.scrollToItem(at: IndexPath(item: self.actualNumberOfTheCell, section: 0), at: .centeredHorizontally, animated: false)
}, completion: nil)
I think you should have to do it with self.view.layoutIfNeeded()
self.appsCollectionView.scrollToItem(at: IndexPath(item: self.actualNumberOfTheCell, section: 0), at: .centeredHorizontally, animated: false)
UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
Hope it will work
Your reused cells might be overlapping because of the sudden scroll. The latest cell might have not been dequeued properly and is perhaps initialized using a content of a previous cell -> which is most likely an empty cell that hasn't been properly displayed during the scroll.
Try to reset your cell content using:
prepareForReuse() inside your cell's controller.
You should reset your UI to a default state here.
Here's the docs link to it
Don't forget to call a UI display/setup method for your cell, which should display your UI elements.
Hope it helps!
I think the issue is caused by collectionView recycling the cell too early, as you are using scrollToItem with animation = false.
I tried to split the animation to several smaller steps, It works, but the scroll is not smooth. Here is the code:
// self is extended from UICollectionView
scrollTo(x: 100, duration: 0.6, count: 4) { (finished) in
}
private func scrollTo(x:CGFloat, duration:TimeInterval, count:Int, completion:#escaping (Bool)->Void)
{
let xOffset = (x - contentOffset.x)/CGFloat(count)
let durationPart = duration/TimeInterval(count)
scrollToPart(xOffset: xOffset, duration: durationPart, count: count, completion: completion)
}
private func scrollToPart(xOffset:CGFloat, duration:TimeInterval, count:Int, completion:#escaping (Bool)->Void)
{
UIView.animate(withDuration: duration, animations: {
self.contentOffset.x += xOffset
}) { (finished) in
if count <= 1
{
completion(finished)
}
else
{
self.scrollToPart(xOffset: xOffset, duration: duration, count: count-1, completion: completion)
}
}
}
I used scrollToItem with animated = true at last.
I have a UICollectionView within a UIViewController with paging enabled. For some strange reason collectionView.scrollToItem works when the direction of the collectionview is vertical but doesn't when direction is horizontal. Is this there something I'm doing wrong or is this supposed to happen?
//Test scrollToItem
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let i = IndexPath(item: 3, section: 0)
collectionView.reloadData()
collectionView.scrollToItem(at: i, at: .top, animated: true)
print("Selected")
}
For iOS 14
Apparently there is a new bug in UICollectionView that is causing scrollToItem to not work when paging is enabled. The work around is to disable paging before calling scrollToItem, then re-enabling it afterwards:
collectionView.isPagingEnabled = false
collectionView.scrollToItem(
at: IndexPath(item: value, section: 0),
at: .centeredHorizontally,
animated: true
)
collectionView.isPagingEnabled = true
Source: https://developer.apple.com/forums/thread/663156
For this part:
collectionView.scrollToItem(at: i, at: .top, animated: true)
When the scroll direction is horizontal you need to use at: left, at: right or at: centeredHorizontally. at: top is for vertical direction.
I had trouble implementing this in a flow layout with entered paging per item. The .centeredHorizontally just wouldn't work for me so i use scroll to rect and Check there is data before scrolling:
if self.collectionView?.dataSource?.collectionView(self.collectionView!, cellForItemAt: IndexPath(row: 0, section: 0)) != nil {
let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(item: data[index], section: 0))?.frame
self.collectionView.scrollRectToVisible(rect!, animated: false)
}
Swift 5.1, Xcode 11.4
collectionView.scrollToItem(at: IndexPath(item: pageNumber , section: 0), at: .centeredHorizontally, animated: true)
self.collectionView.setNeedsLayout() // **Without this effect wont be visible**
I try a lot of things and fail. This saves my day.
func scrollToIndex(index:Int) {
let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame
self.collectionView.scrollRectToVisible(rect!, animated: true)
}
Reference: https://stackoverflow.com/a/41413575/9047324
I have this issue: when button tapped (for horizontal collection scroll to next item) it always returns to first item with UI bug.
The reason was in this parameter: myCollection.isPagingEnabled = true
Solution: just disable paging before scroll to next item, and enable it after scroll.
After adding items to collectionView and reloadData(), scrollToItem was not working because reloading data has not finished yet.
Because of this I added performBatchUpdates like this :
self.dataSource.append("Test")
self.collectionView.performBatchUpdates ({
self.collectionView.reloadData()
}, completion: { _ in
self.collectionView.scrollToItem(at: IndexPath(item: 3, section: 0),
at: .centeredHorizontally,
animated: false)
})
I know it's not about this question but it will be helpful for this title.
For me, I had to scroll collection view on main thread like:
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true)
}
This will not work if you call scrollToItem before viewDidLayoutSubviews. Using scrollToItem in viewDidLoad will not work. So call this function after viewDidLayoutSubviews() is completed.
For iOS 14+
It's so stupid but it works.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
self?.collectionView.scrollToItem(at: i, at: .top, animated: true)
}
Swift 3:
This worked for me on horizontal collection view.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Show 14th row as first row
self.activityCollectionView?.scrollToItem(at: IndexPath(row: 14, section: 0), at: UICollectionViewScrollPosition.right, animated: true)
}
You can choose whether the desired cell at index to be on right or left on scroll position.
UICollectionViewScrollPosition.right or UICollectionViewScrollPosition.left.
Swift 5 if with animation horizontally
func scrollToIndex(index:Int) {
self.collectionView?.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true)
}
Your example:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
print("Selected: \(indexPath.row)")
collectionView.reloadData()
}
As #Dheeraj Agarwal points out, none of the 'ScrollTo' functionality of UICollectionView OR UIScrollView will seem to work properly if it is called before the view has been laid out. To be accurate, I think they WORK, but the effects are immediately nullified because laying out a UICollectionView causes it to reset to its minimum bounds, probably because of all the cell layout functions that will trigger, and the fact its content size may change.
The solution is to make sure this function is called after layout occurs, but it's not that simple. It's entirely likely that a collection view may be told to layout its content again and again in response to various changes - setting delegates, the contents updating, the view controller being added to a parent and therefore changing size. Each time this happens it'll reset to 0:0 offset.
You'll therefore have to keep a reference to the desired offset / cell index / frame until such a time as you are CERTAIN there will be no more unexpected layout updates. You can't just nil it out immediately as your collection view's layout might change multiple times before the view appears. I'm currently storing a frame in an attribute and calling the function in layoutFrames every time (my collection view's parent is a custom view, not a view controller). Although this has the slightly annoying feature of scrolling back again if the user rotates their phone, I consider it acceptable since this is a custom keyboard and most users will work with it in one orientation or the other, they won't keep flipping their phone around just to select a single value.
Solutions like calling DispatchQueue.main.asyncAfter are fragile. They work because the function call gets delayed until after the first layout occurs, but this may not always-and-forever solve the problem.
I guess the 'Scroll To' functions were only ever intended to be used in response to direct user input after the collection view is already populated.
CollectionView.isPagingEnabled = false
CollectionView.scrollToItem(at:IndexPath(item: YourcellIndex(4), section: at which section you want cell(0)), at: .centeredHorizontally, animated: false)
CollectionView.layoutSubviews()
CollectionView.isPagingEnabled = true
sometimes you can set
collectionView.collectionlayout.invalidate()
collectionView.scrollToItem(row:2,section:0)
If you have networking which can make disturb main thread, you have to avoid or after finish that, have to apply this code.
for example
self.group.enter()
some thread
self.group.leave()
I need to scroll to bottom. I have a chat app like whatsapp. So when view appears table view should show last row. I am achiving this with following line and works nice.
tableView.setContentOffset(CGPointMake(0, CGFloat.max), animated: false)
Also I need to scroll to bottom when keyboard appears. I am using Auto Layout and above line is not working. For to do this i am using following line:
func scrollToLastRow(animated: Bool) {
if self.numberOfRowsInSection(0) > 0 {
self.scrollToRowAtIndexPath(NSIndexPath(forRow: self.numberOfRowsInSection(0) - 1, inSection: 0), atScrollPosition: .Bottom, animated: animated)
}
}
This is a extension for Tableview.
This solution is working fine when there is no too much message. Then I tried with 5000 messages (so tableview have 5000 rows, but i am paging them) And when keyboard appears i see cpu usage is %98-100. I think the second code is problem for pagination, it causes loading every message to ram and my app freezes and receiving ram warning.
How to scroll to bottom without any performance issue?
If you have pagination, you can try to only load your current page as well as the final page, assuming you have 20 messages in each page, in this case your table have 40 rows only. Then you can use your function:
func scrollToLastRow(animated: Bool) {
if self.numberOfRowsInSection(0) > 0 {
self.scrollToRowAtIndexPath(NSIndexPath(forRow: self.numberOfRowsInSection(0) - 1, inSection: 0), atScrollPosition: .Bottom, animated: animated)
}
}
try this method :
let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)
if numberOfRows > 0 {
let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: (numberOfSections-1))
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
})
If your are creating IM app. I recommend you reverse the tableView.
So the first row appears at bottom, and don't needs scrolling at beginning anymore.
Here is a cocoapod could help: https://github.com/marty-suzuki/ReverseExtension
If you stil want to scroll to specific row
implement the UIScrollViewDelegate.scrollViewDidEndScrollingAnimation.
and goes like this.
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if scrollView.contentSize.height > lastContentHeight {
self.tableView.scrollToBottom()
self.lastContentHeight = scrollView.contentSize.height
}
}