UITableView Refresh without scrolling - ios

I have a _TableView with items , and I want to set automatic refresh,and I don't want it to scroll on refresh , lets say user scrolled 2 pages down , and the refresh trigered -> so I want to put the refreshed content to the top of the table without interupting user's scrolling
Assume user was on row 18
and now the _dataSource is refreshed so it fetched lets say 4 items , so I want user to stay on the item he was.
What would be the best approach to achieve it ??

For Swift 3+:
You need to save the current offset of the UITableView, then reload and then set the offset back on the UITableView.
I have created this function for this purpose:
func reload(tableView: UITableView) {
let contentOffset = tableView.contentOffset
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.setContentOffset(contentOffset, animated: false)
}
Simply call it with: reload(tableView: self.tableView)

SWIFT 3
let contentOffset = self.tableView.contentOffset
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.tableView.setContentOffset(contentOffset, animated: false)
This is error of iOS8 when using UITableViewAutomatic Dimension. We need store the content offset of table, reload table, force layout and set contenOffset back.
CGPoint contentOffset = self.tableView.contentOffset;
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
[self.tableView setContentOffset:contentOffset];

I am showing if only one row is being added. You can extend it to multiple rows.
// dataArray is your data Source object
[dataArray insertObject:name atIndex:0];
CGPoint contentOffset = self.tableView.contentOffset;
contentOffset.y += [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView reloadData];
[self.tableView setContentOffset:contentOffset];
But for this to work you need to have defined - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath the method. Or else, you can directly give your tableview row height if it is constant.

Just set estimatedRowHeight to maximum possible value.
self.tableView.estimatedRowHeight = 1000
self.tableView.estimatedSectionFooterHeight = 100.0
self.tableView.estimatedSectionHeaderHeight = 500.0
That's it!!
Note:
Please do not use FLT_MAX, DBL_MAX value. May be it will crash your app.

I'm doing it this way:
messages.insertContentsOf(incomingMsgs.reverse(), at: 0)
table.reloadData()
// This is for the first load, first 20 messages, scroll to bottom
if (messages.count <= 20) {
let indexToScroll = NSIndexPath(forRow: saferSelf.messages.count - 1, inSection: 0)
table.scrollToRowAtIndexPath(indexToScroll, atScrollPosition: .Top , animated: false)
}
// This is to reload older messages on top of tableview
else {
let indexToScroll = NSIndexPath(forRow: incomingMsgs.count, inSection: 0)
table.scrollToRowAtIndexPath(indexToScroll, atScrollPosition: .Top , animated: false)
// Remove the refreshControl.height + tableHeader.height from the offset so the content remain where it was before reload
let theRightOffset = CGPointMake(0, table.contentOffset.y - refreshControl.frame.height - table.headeView.frame.height)
table.setContentOffset(theRightOffset, animated: false)
}
...also, since I use dynamic cell height, to avoid some weirdness, the estimation is cached:
var heightAtIndexPath = [NSIndexPath: CGFloat]()
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return heightAtIndexPath[indexPath] ?? UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
heightAtIndexPath[indexPath] = cell.frame.height
}

Use Extension
create UITableViewExtensions.swift and add following:
extension UITableView {
func reloadDataWithoutScroll() {
let offset = contentOffset
reloadData()
layoutIfNeeded()
setContentOffset(offset, animated: false)
}
}

In iOS 12.x, using Xcode 10.2.1, an easier option is.
UIView.performWithoutAnimation {
let loc = tableView.contentOffset
tableView.reloadRows(at: [indexPath], with: .none)
tableView.contentOffset = loc
}
This works better than following; it shakes at times when the row is not fully visible.
let contentOffset = self.tableView.contentOffset
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
self.tableView.setContentOffset(contentOffset, animated: false)

Swift 4.2 : Simple Solution
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 0
self.tableView.estimatedSectionHeaderHeight = 0
self.tableView.estimatedSectionFooterHeight = 0
}
//And then simply update(insert, reloadSections, delete etc) your tableView or reload
tableView.reloadData()
//or
UIView.performWithoutAnimation {
tableView.beginUpdates()
.....
tableView.endUpdates()
}

This code will prevent unnecessary animation and maintain the scroll view's content offset, it worked fine for me.
let lastScrollOffset = tableView.contentOffset
tableView.beginUpdates()
tableView.reloadData()
tableView.endUpdates()
tableView.layer.removeAllAnimations()
tableView.setContentOffset(lastScrollOffset, animated: false)

When you want to reload you have to
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
and also use this UITableViewDelegate
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 'your maximum cell's height'
}
and your tableView will remain on the previous scroll position without scrolling

try to replace
reloadData with
tableView.reloadRows(at: tableView!.indexPathsForVisibleRows!, with: .none),
but you should be care about no cells, if no cells, this method should cause crash.

i wrote something that works perfect for me:
extension UIScrollView {
func reloadDataAndKeepContentOffsetInPlace(reloadData:(() -> Void)) {
let currentContentHeight = contentSize.height
if currentContentHeight == .zero {
reloadData()
return
}
reloadData()
layoutIfNeeded()
let newContentHeight = self.contentSize.height
DispatchQueue.main.async {
var contentOffset = self.contentOffset
contentOffset.y += newContentHeight - currentContentHeight
self.setContentOffset(contentOffset, animated: false)
}
}
}
use like this:
self.reloadSomeData()
collectionView.reloadDataAndKeepContentOffsetInPlace { [weak self] in
guard let self = self else { return }
self.collectionView.reloadData()
}

Try the following.
tableView.estimatedRowHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.estimatedSectionFooterHeight = 0
Source: https://developer.apple.com/forums/thread/86703

Related

updating tableViewCell's height and moving tableView at the same time

i'm moving up my tableView (via setting contentOffset) and changing a specific (row no. 1 here ) cell's height at the same time , thats why i'm getting a shaky animation and also tableView restores itself to the default position (which is not desired behavior )
my code :
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double)
keyboardHeight = keyboardRectangle.height
accurateheight = accurateheight - (keyboardHeight + inputToolbar.frame.size.height) // accurateHeight is the desired CGFloat value that i want
self.tableView.beginUpdates()
self.tableView.endUpdates()
let frame = tableView.rectForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))
defaultRowHeight = frame.height
let cgpoint = CGPointMake(0, (CGFloat(-64 + defaultRowHeight)))
self.tableView.setContentOffset(cgpoint, animated: true) // here i'm moving up my tableView
}
in my heightForRowAtIndexPath:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 44
}else {
return accurate height // cell's height which i'm changing
}
}
i also tried to update only specific row (the ones that i'm changing height of) like this :
var indexPath = NSIndexPath(forRow: 1, inSection: 0)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
but the above didnt worked also sometimes my keyboard was not popping up.
how can i move (scroll up) my tableView and change a cell's height at the same time ?? any clue ?

UITableView Row Separator Lines Not Behaving Correctly With Expanding Cell

I am expanding my cells with the following code:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let originalHeight: CGFloat = 48.0
let expandedHeight: CGFloat = 135
let indexPath = indexPath
if self.expandButtonTappedIndexPath != nil {
if indexPath == self.expandButtonTappedIndexPath! {
return expandedHeight
} else {
return originalHeight
}
} else {
return originalHeight
}
}
And
#IBAction func expandButtonTapped(sender: AnyObject) {
switch self.expandButtonTappedIndexPath {
case nil:
self.expandButtonTappedIndexPath = indexPath
default:
if self.expandButtonTappedIndexPath! == indexPath {
self.expandButtonTappedIndexPath = nil
} else {
self.expandButtonTappedIndexPath = indexPath
//self.tableView.scrollToRowAtIndexPath(indexPath!, atScrollPosition: .Top, animated: true)
}
}
}
Here is the picture of the problem:
All my previous times in expanding my cell, I never had this problem of that separator line appearing there and not under the expanded cell. But for whatever reason this time, it's appearing and I have no idea how to put it under the expanded cell.
And the following is how I set up my cell in the MainStoryBoard:
Now, I've tried changing the original height and that causes that line to move around. But I want the original height to be 48.0 and I want the separator line to move to the bottom of the expanded cell not awkwardly in the middle.
Any suggestions on how to fix this problem? Thank you so much in advance for your help :)
I apologize. I should have done more research. The answer is found here:
UITableView displays separator at wrong position in iOS8 for some cells
I just have to call the super class in my layoutSubviews() function in my cell. I apologize like so:
override func layoutSubviews() {
super.layoutSubviews()
}

UIWebView's entire contents embedded in UITableView

I've been struggling with this for two days, so I come hat in hand to the wise people of the internet.
I am showing an article as part of my UITableView. For this to display correctly, I need to give the delegate a height for the cell, which I want to be the same as the UIWebView's height, so I can disable scroll on the WebView and display the web content in its entirety as a static cell.
My first approach was to render it in the heightForRowAtIndexpathmethod, but this did obviously not work as I need the wait for the UIWebViewDelegate to tell me when the web view is fully loaded and has a height. After a while I found a working solution, which used the web view delegate to refresh the cell height when the web view was loaded.
The works fine until the screen size changes. Either from rotate or from full-screening my UISplitView. I forced an update on it in the didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation), but this causes it to flash about 10 times before settling into the correct height. I logged this change, and it seems the WebView is calling itself multiple times, causing a loop.
As seen in this log, starting from when I rotated the screen.
It flashes once every time it reloads, and as you can see, it reloads itself a bunch of times.
So. I need a way to show an entire web views content inside a uitableview, and reliably get the height when the screen size changes. If anyone has managed this in any way before, please tell me. I will give a bounty and my firstborn child to anyone who can resolve this, as it's driving me insane.
Here's my relevant code.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.row {
case 4:
//Content
print("Height for row called")
return CGFloat(webViewHeight)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.row){
//HTML Content View
case 4:
let cell = tableView.dequeueReusableCellWithIdentifier("ContentCell", forIndexPath: indexPath)
var contentCell = cell as? ContentCell
if contentCell == nil {
contentCell = ContentCell()
}
contentCell?.contentWebView.delegate = self
contentCell?.contentWebView.scrollView.userInteractionEnabled = false
contentCell?.contentWebView.loadHTMLString((post?.contentHTML)!, baseURL: nil)
print("Cell For row at indexpath called")
return contentCell!
}
func webViewDidFinishLoad(webView: UIWebView) {
updateHeight()
}
func updateHeight(){
let webView = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0)) as! ContentCell).contentWebView
if self.webViewHeight != Double(webView.scrollView.contentSize.height) {
print("Previous WV Height = \(self.webViewHeight), New WV Height = \(webView.scrollView.contentSize.height)")
self.webViewHeight = Double(webView.scrollView.contentSize.height)
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .Automatic)
} else {
return
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
print("rotated")
self.updateHeight()
//tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .Automatic)
}
I solved this by changing the .Automatic to .None in the row change animation. Its still a bad solution, but at least it doesn't flicker anymore.
I would recommend that you calculate the web view height independently of the table view and store the dimension as part of the data itself and use it return in heightForRowAtIndexPath call. Its a easier that way since you don't have to deal with calculating the table height during table view display. When the html content is not loaded use a standard height and a message for the web view.
I don't see a problem in your implementation. Trey few things
There are few things you can check
func webViewDidFinishLoad(webView: UIWebView) {
updateHeight()
//This function may get called multiple times depending on webpage.
}
//Use
self.tableView.beginUpdates()
self.tableView.endUpdates()
//Instead of
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .None)
func updateHeight(){
let webView = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0)) as! ContentCell).contentWebView
if self.webViewHeight != Double(webView.scrollView.contentSize.height)
{
print("Previous WV Height = \(self.webViewHeight), New WV Height = \(webView.scrollView.contentSize.height)")
self.webViewHeight = Double(webView.scrollView.contentSize.height)
self.tableView.beginUpdates()
self.tableView.endUpdates()
// tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .None)
} else {
return
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)
{
print("rotated")
let webView = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 4, inSection: 0)) as! ContentCell).contentWebView
webView.reload();
}
You will need to reload webview on orientation change.

UITableView indexPath of last row

I am attempting to make the last row in a UITableView visible, after it has been added. Right now, when I add a row and call reloadData, the table goes to the top.
I figure if I get the indexPath for the last row, that I can select that row and it should appear in the list. I am unsure of how to get that value, or even if I am approaching this correctly.
How do I get an indexPath for a specific row?
Please note that, you don't need to call the reloadData to make the last row visible. You can make use of scrollToRowAtIndexPath method.
You can use the below code to achieve your goal.
// First figure out how many sections there are
let lastSectionIndex = self.tblTableView!.numberOfSections() - 1
// Then grab the number of rows in the last section
let lastRowIndex = self.tblTableView!.numberOfRowsInSection(lastSectionIndex) - 1
// Now just construct the index path
let pathToLastRow = NSIndexPath(forRow: lastRowIndex, inSection: lastSectionIndex)
// Make the last row visible
self.tblTableView?.scrollToRowAtIndexPath(pathToLastRow, atScrollPosition: UITableViewScrollPosition.None, animated: true)
Swift 4.0:
tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.none, animated: true)
You can use scrollToRowAtIndexPath with extension:
In Swift 3:
extension UITableView {
func scrollToLastCell(animated : Bool) {
let lastSectionIndex = self.numberOfSections - 1 // last section
let lastRowIndex = self.numberOfRows(inSection: lastSectionIndex) - 1 // last row
self.scrollToRow(at: IndexPath(row: lastRowIndex, section: lastSectionIndex), at: .Bottom, animated: animated)
}
}
Shamsudheen TK's answer will crash
if there is no rows/sections in tableview.
The following solution to avoid crash at run time
extension UITableView {
func scrollToBottom() {
let lastSectionIndex = self.numberOfSections - 1
if lastSectionIndex < 0 { //if invalid section
return
}
let lastRowIndex = self.numberOfRows(inSection: lastSectionIndex) - 1
if lastRowIndex < 0 { //if invalid row
return
}
let pathToLastRow = IndexPath(row: lastRowIndex, section: lastSectionIndex)
self.scrollToRow(at: pathToLastRow, at: .bottom, animated: true)
}
}
Note: If you are trying to scroll to bottom in block/clousure then you need to call this on main thread.
DispatchQueue.main.async {
self.tableView.scrollToBottom()
}
Hope this will helps other
As suggested by others get indexPath for perticular sections like section 0.
After that call...add this methos in cellFOrROwAtIndex
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; ..to scroll to specific indexPath in TableView.
Note:-But it still need scrolling of tableview in Downward direction.
You shouldn't be using -reloadData for this use case. What you're looking for is -insertRowsAtIndexPaths:withRowAnimation:.
Feel free to ask if you want some usage examples or a more detailed explanation as to why using -reloadData send you to the top of the UITableView.
Not mandatorily required to get the indexpath of last row.
You can set the CGPoint of UITableview to show a last row you added.
I always use this code in my chat application to show a last added message.
//Declaration
#IBOutlet weak var tableview: UITableView!
//Add this executable code after you add this message.
var tblframe: CGRect = tableview.frame
tblframe.size.height = self.view.frame.origin.y
tableview.frame = tblframe
var bottomoffset: CGPoint = CGPointMake(0, tableview.contentSize.height - tableview.bounds.size.height)
if bottomoffset.y > 0 {
tableview.contentOffset = bottomoffset;
}
I hope it will work for you.
Thanks.
Swift 5.0 +
extension UITableView {
func isLastVisibleCell(at indexPath: IndexPath) -> Bool {
guard let lastIndexPath = indexPathsForVisibleRows?.last else {
return false
}
return lastIndexPath == indexPath
}
}

Start UICollectionView at a specific indexpath

I currently have a collection view that does horizontal paging where each cell is fullscreen. What I want to do is for the collectionview to start at a specific index when it shows.
Right now I'm using scrollToItemAtIndexPath:atScrollPosition:animated: with animated set to NO but that still loads the first index first before it can scroll to the specific item. It also seems I can only use this method in ViewDidAppear so it shows the first cell and then blinks to the cell that I want to show. I hide this by hiding the collection view until the scroll has finished but it doesn't seem ideal.
Is there any better way to do this other than the way I described it?
Thanks!
So I solved this a different way, using the UICollectionViewDelegate method and a one-off Bool:
Swift 2:
var onceOnly = false
internal func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if !onceOnly {
let indexToScrollTo = NSIndexPath(forRow: row, inSection: section)
self.problemListCollectionView.scrollToItemAtIndexPath(indexToScrollTo, atScrollPosition: .Left, animated: false)
onceOnly = true
}
}
Swift 3:
var onceOnly = false
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
let indexToScrollTo = IndexPath(item: row, section: section)
self.problemListCollectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
onceOnly = true
}
}
This code is executed before any animation occurs (so it really loads to this point), which is better than attempting to call in viewDidAppear, and I didn't have success with it in viewWillAppear.
To solve this problem I partially used the greenhouse answer.
/// Edit
var startIndex: Int! = 0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
collectionView.scrollToItemAtIndexPath(
NSIndexPath(forItem: 0, inSection: startIndex),
atScrollPosition: .None,
animated: false)
}
The problem seems to be in the wrong collectionView size. After setting the layout scrollToItemAtIndexPath produces the needed result.
It also seems that this problem only persists when a Collection View is used inside a UIViewController.
Unfortunately, every single one of these existing answers is at least partly wrong or does not answer the exact question being asked. I worked through this issue with a co-worker who was not helped by any of these responses.
All you need to do is set the content offset without animation to the correct content offset and then call reload data. (Or skip the reloadData call if it has not been loaded at all yet.) You should do this in viewDidLoad if you never want the first cell to be created.
This answer assumes the collection view scrolls horizontally and the size of the cells are the same size as the view but the concept is the same if you want to scroll vertically or the cells are a different size. Also if your CollectionView has more than one section you have to do a bit more math to calculate the content offset but the concept is still the same.
func viewDidLoad() {
super.viewDidLoad()
let pageSize = self.view.bounds.size
let contentOffset = CGPoint(x: pageSize.width * self.items.count, y: 0)
self.collectionView.setContentOffset(contentOffset, animated: false)
}
A simpler solution inspired by others:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: lastIndexPath, section: 0), at: .centeredHorizontally, animated: false)
}
}
It will work if you put the code inside DispatchQueue.main.async block.
Swift 3.0 tested and works.
var onceOnly = false
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
//set the row and section you need.
let indexToScrollTo = IndexPath(row: 1, section: indexPath.section)
self.fotmCollectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
onceOnly = true
}
}
Here is what worked for me (in a UICollectionViewController class):
private var didLayoutFlag: Bool = false
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let collectionView = self.collectionView {
if !self.didLayoutFlag {
collectionView.scrollToItemAtIndexPath(self.viewModel.initialIndexPath, atScrollPosition: .None, animated: false)
self.didLayoutFlag = true
}
}
}
Pass the indexPath from the first VC to the collection view in the DidSelectItemAtIndexPath method. In viewDidLoad of your collection view, use the method scrollToItemAtIndexPath:atScrollPosition:animated: Set animated to NO and atScrollPosition to UICollectionViewScrollPositionNone. Like this:
[self.collectionView scrollToItemAtIndexPath:self.indexPathFromVC atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
this seemed to work for me:
- (void)viewDidLayoutSubviews
{
[self.collectionView layoutIfNeeded];
NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:someInt inSection:currentItem.section];
[self.collectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
I came here having this same issue and found that in my case, this issue was caused my the ViewController in my storyboard being set as 'freeform' size.
I guess viewWillLayoutSubviews gets called to calculate the correct size when the view is first loaded if the storyboard's dimensions leave this unclear. (I had sized my viewController in my storyboard as to be 'freeform' so I could make it very tall to see/edit many cells in long tableView inside my collectionView).
I found that victor.vasilica's & greenhouse's approach re: putting the 'scrollToRow' command in viewWillLayoutSubviews did work perfectly to fix the issue.
However, I also found that once I made the VC in my storyboard 'fixed' size again, the issue immediately went away and I was able to set the initial cell from viewWillAppear. Your situation may be different, but this helped me understand what was going on in my situation and I hope my answer might help inform others with this issue.
Just found me in the same problem, and make it work by adding this piece of code in willDisplayCell delegate call
private var firstLoad: Bool = true
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if self.firstLoad {
let initialIndexPath = <initial index path>
collectionView.scrollToItem(
at: initialIndexPath,
at: <UICollectionView.ScrollPosition>,
animated: false
)
self.firstLoad = false
}
}
Hey I have Solved With Objective c .
I think this is useful for you.
You can convert Objective c to swift as well .
Here is my Code:
**In My case , On button click I activate the specific index , that is 3 **
for Vertical
- (IBAction)Click:(id *)sender {
NSInteger index=3;
CGFloat pageHeight = self.collectionView.frame.size.height;
CGPoint scrollTo = CGPointMake(0, pageHeight * index);
[self.collectionView setContentOffset:scrollTo animated:YES];
}
For Horizontal
- (IBAction)Click:(id *)sender {
NSInteger index=3;
CGFloat pageWidth = self.collectionView.frame.size.width;
CGPoint scrollTo = CGPointMake(pageWidth * index, 0);
[self.collectionView setContentOffset:scrollTo animated:YES];
}
I hope it may help You.

Resources