59

I am using iOS 8 new self-sizing cells. Visually it works good - each cell gets its right size. However, if I try to scroll to the last row, the table view doesn't seem to know its right size. Is this a bug or is there a fix for that?

Here's how to recreate the problem:

Using this project - TableViewCellWithAutoLayoutiOS8 (referenced from this SO answer), I got the auto-resizing cells as expected.

However, if I am calling the scrollToRowAtIndexPath function, like this:

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: model.dataArray.count - 1, inSection: 0), atScrollPosition: .Bottom, animated: true)

I do not get to the last row - It only gets me around halfway there.

Even by trying to use a lower level function like this:

tableView.setContentOffset(CGPointMake(0, tableView.contentSize.height - tableView.frame.size.height), animated: true)

The result is not as expected, it won't get to the end. If I click it a lot of times or wait a few moments, eventually it will get to the right place. It seems the tableView.contentSize.height is not set correctly, so the iOS "doesn't know" where that last cell is.

Would appreciate any help.

Thanks

Community
  • 1
  • 1
BenB
  • 1,522
  • 1
  • 14
  • 26
  • Some questions: Does it work for rows towards the beginning? Is there a cut off point where it stops working? Is it a problem with one section or all sections? Does your auto layout have any errors? Is your estimated cell height very different from your cell's actual height? Finally, if you have a repeatable bug then please report it to: https://bugreport.apple.com – Robotic Cat Sep 05 '14 at 13:30
  • It's not accurate for any row index I insert. Tried it with only 1 section. No errors reported in IB/console. Estimated height seems to be about the average. Seems like a bug I think, but maybe this post will help :) Thanks. – BenB Sep 05 '14 at 13:59
  • even the ios 8 & Xcode GM seed didn't fix this one :( – BenB Sep 10 '14 at 20:52
  • Time to log a bug although I am surprised that no-one else has come across this. It's not an uncommon pattern. – Robotic Cat Sep 10 '14 at 22:28
  • Yeh, I was surprised too. Anyway, already filed a bug. Will update here if there's anything new. Thanks. – BenB Sep 11 '14 at 12:38
  • 1
    I'm having the same issue. One additional side-effect of this bug is that when you scroll to the "bottom" (or somewhere close to that) and then you scroll up, the table view jumps when recalculating the correct cell size from the top rows. This happens if you scroll:animated NO (which doesn't give time for the table view to load the top cells). – Gui Moura Oct 14 '14 at 00:43
  • Please Check this..http://stackoverflow.com/questions/11928085/uitableview-not-visible-the-last-cell-when-scroll-down/32271311#32271311 – Narasimha Nallamsetty Aug 28 '15 at 12:41
  • I have this problem when one or some cells height is large (for example 500). – Hamed Mar 03 '20 at 05:58

12 Answers12

33

Update: Jun 24, 2015

Apple has addressed most of these bugs as of the iOS 9.0 SDK. All of the issues are fixed as of iOS 9 beta 2, including scrolling to the top & bottom of the table view without animation, and calling reloadData while scrolled in the middle of the table view.

Here are the remaining issues that have not been fixed yet:

  1. When using a large estimated row height, scrolling to the last row with animation causes the table view cells to disappear.
  2. When using a small estimated row height, scrolling to the last row with animation causes the table view to finish scrolling too early, leaving some cells below the visible area (and the last row still offscreen).

A new bug report (rdar://21539211) has been filed for these issues relating to scrolling with animation.

Original Answer

This is an Apple bug with the table view row height estimation, and it has existed since this functionality first was introduced in iOS 7. I have worked directly with Apple UIKit engineers and developer evangelists on this issue -- they have acknowledged that it is a bug, but do not have any reliable workaround (short of disabling row height estimation), and did not seem particularly interested in fixing it.

Note that the bug manifests itself in other ways, such as disappearing table view cells when you call reloadData while scrolled partially or fully down (e.g. contentOffset.y is significantly greater than 0).

Clearly, with iOS 8 self sizing cells, row height estimation is critically important, so Apple really needs to address this ASAP.

I filed this issue back on Oct 21 2013 as Radar #15283329. Please do file duplicate bug reports so that Apple prioritizes a fix.

You can attach this simple sample project to demonstrate the issue. It is based directly on Apple's own sample code.

Cœur
  • 37,241
  • 25
  • 195
  • 267
smileyborg
  • 30,197
  • 11
  • 60
  • 73
  • 1
    Or you may use https://github.com/slackhq/SlackTextViewController and get all over the problem we're still waiting Apple to fix – abinop Oct 08 '14 at 06:19
  • 2
    @abinop How does Slack's text view controller provide a general case substitute/workaround for a UITableView? I think that's only appropriate for some specific use cases, and certainly not going to be worth reimplementing existing code. – smileyborg Oct 08 '14 at 06:44
  • it depends on how bad one needs the list to scroll down and also knowing that the problem exists for so much time and there might not be a solution soon.I am going to try for myself to extend Slack and see how it goes.It may be useful for someone who is in the start of developing a project. – abinop Oct 08 '14 at 06:55
  • 1
    @abinop IIRC they use an upside down table view in their internal implementation. I wouldn't get too excited :) – smileyborg Oct 08 '14 at 06:57
  • I created an example that shows clearly what the problem is, can be found here https://github.com/abinop/Auto-height-ios8-UITableView-scroll-problem .I will post it as a bug report. – abinop Oct 10 '14 at 13:27
  • Good news! Apple has finally started addressing this radar and the associated issues, as of iOS 9 beta 1. Here are the results of my testing so far: https://twitter.com/smileyborg/status/608679741277634560 Still some open issues, hopefully they will get fixed in subsequent iOS 9 betas! – smileyborg Jun 10 '15 at 17:01
20

This has been a very annoying bug, but I think I found a permanent solution, though I cannot fully explain why.

Call the function after a tiny (unnoticed) delay:

let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(time, dispatch_get_main_queue(), {
  tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: model.dataArray.count - 1, inSection: 0), atScrollPosition: .Bottom, animated: true)
})

Do tell me if this works for you as well.

abinop
  • 3,153
  • 5
  • 32
  • 46
  • This worked for me. It allows my call to `reloadData` to finish before trying to reset scroll positions. I am using iOS 8.1 with auto-height cells. – Eric Baker Jan 10 '15 at 19:56
  • 6
    This does not seem to work for me, even with a greater time delay. =( – Xerion Feb 19 '15 at 19:41
  • This worked for me, but only if I did it twice. Once right away to go to the wrong location, then after a delay. I'm not sure how reliable it is. http://stackoverflow.com/questions/28613995/ios8-uitableview-scrolltorowatindexpath-inaccurate-with-auto-sizing-cells – iseletsky Feb 20 '15 at 00:49
  • yes this worked, however i try to make less dirty code : dispatch_after(0, dispatch_get_main_queue(), ^{ [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_myGroup.shouts.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; }); – maddy May 26 '15 at 06:20
  • This is working in 8.2. Without this workaround the scroll bug is still there. – creality Jun 09 '15 at 14:17
  • I'm not proud of it, but I found that this only worked if I didn't animate the scrolling, and called scrollToRowAtIndexPath twice with a delay between. Ugly! – John M. P. Knox Jun 22 '15 at 20:26
  • This renders cells per each dispatch_after and looks ugly. My solution does not render, only lays out them. http://stackoverflow.com/a/33515872/1474113 – ypresto Nov 04 '15 at 07:22
13

It is definitely a bug from Apple. I also have this problem. I solved this problem by calling "scrollToRowAtIndexPath" method twice example code is:

        if array.count > 0 {
        let indexPath: NSIndexPath = NSIndexPath(forRow: array.count - 1, inSection: 0)
        self.tblView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
        let delay = 0.1 * Double(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

        dispatch_after(time, dispatch_get_main_queue(), {
            self.tblView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
        })
    }
Bhavesh Tiwari
  • 155
  • 1
  • 3
5

I found a temporary workaround that might be helpful until Apple decides to fixes the many bugs that have been plaguing us.

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = [self findTextForIndexPath:indexPath];
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:13];
    CGRect estimatedHeight = [text boundingRectWithSize:CGSizeMake(215, MAXFLOAT)
                                                options:NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{NSFontAttributeName: font}
                                                context:nil];
    return TOP_PADDING + CGRectGetHeight(estimatedHeight) + BOTTOM_PADDING;
}

This is not perfect, but it did the job for me. Now I can call:

- (void)scrollToLastestSeenMessageAnimated:(BOOL)animated
{
    NSInteger count = [self tableView:self.tableView numberOfRowsInSection:0];
    if (count > 0) {
        NSInteger lastPos = MAX(0, count-1);
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:lastPos inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}

On viewDidLayoutSubviews and it finds the correct place on the bottom (or a very close estimated position).

I hope that helps.

Gui Moura
  • 1,360
  • 1
  • 16
  • 26
  • I'm looking since days for a solution, but this is honestly the best workaround! Thanks! – cldrr Jul 16 '15 at 09:58
1

For my case, I found a temporary workaround by not suggesting an estimated cell height to the program. I did this by commenting out the following method in my code:

- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath

However, please take note that doing so may affect the user experience when the user scrolls, if your cells varies a lot compared to each other. For my case, no noticeable difference so far.

Hope it helps!

Marcus
  • 548
  • 1
  • 5
  • 13
1

I have this problem in Swift 5 iOS 13 yet, this solved my problem

 DispatchQueue.main.async { [weak self] in
    self?.tableView.reloadData()
    self?.tableView.scrollToRow(at: indexPath, at: .middle, animated: false)
 }
Hamed
  • 1,678
  • 18
  • 30
0

My solution was to use the size of the storyboard as the estimate.

So instead of this:

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {   
return UITableViewAutomaticDimension;

}

I did something like this:

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { 

MyMessageType messageType = [self messageTypeForRowAtIndexPath:indexPath];

switch (messageType) {

    case MyMessageTypeText:
        return 45;
        break;

    case MyMessageTypeMaybeWithSomeMediaOrSomethingBiggerThanJustText:
        return 96;
        break;

    default:
        break;
 }
}

I'm writing a chat table view so it is likely that many of my cells, specifically that text type will be larger than what is in IB, especially if the chat message is very long. This seems to be a pretty good...well...estimate and scrolling to the bottom gets pretty close. It seems to be slightly worse as the scrolling gets longer, but that is to be expected I suppose

Roderic Campbell
  • 719
  • 5
  • 14
0

Just call tableview reloadData after viewDidAppear can solve the problem

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}
Evan JIANG
  • 690
  • 6
  • 5
0

Although as smileyborg's answer it is bug in iOS 8.x, it should be fixed in all platforms which you supports...

To workaround on pre-iOS9, below code do the trick without any dispatch_async or dispatch_after. Tested on iOS 8.4 simulator.

UPDATE: Calling (only) layoutIfNeeded does not work when view controller become visible by UIPageViewController being scrolled. So use layoutSubviews (or maybe setNeedsLayout + layoutIfNeeded) instead.

// For iOS 8 bug workaround.
// See https://stackoverflow.com/a/33515872/1474113
- (void)scrollToBottomForPreiOS9
{
    CGFloat originalY, scrolledY;
    do {
        // Lay out visible cells immediately for current contentOffset.
        // NOTE: layoutIfNeeded does not work when hosting UIPageViewController is dragged.
        [self.tableView layoutSubviews];
        originalY = self.tableView.contentOffset.y;
        [self scrollToBottom];  // Call -scrollToRowAtIndexPath as usual.
        scrolledY = self.tableView.contentOffset.y;
    } while (scrolledY > originalY);
}
Community
  • 1
  • 1
ypresto
  • 975
  • 1
  • 13
  • 23
0

I had the same problem when creating a chat tableView with different height of cells. I call the code below in viewDidAppear() lifecycle method:

// First figure out how many sections there are
let lastSectionIndex = self.tableView.numberOfSections - 1

// Then grab the number of rows in the last section
let lastRowIndex = self.tableView.numberOfRowsInSection(lastSectionIndex) - 1

// Now just construct the index path
let pathToLastRow = NSIndexPath(forRow: lastRowIndex, inSection: lastSectionIndex)

// Make the last row visible
self.tableView.scrollToRowAtIndexPath(pathToLastRow, atScrollPosition: UITableViewScrollPosition.None, animated: true)

Please let me know if that worked for you too.

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Stefan Olaru
  • 63
  • 13
-1

From the storyboard window click in a blank area to deselect all views then click the view that has the table view in it and then click the Resolve Auto Layout Issue icon and select Reset to Suggested Constraints

enter image description here enter image description here

kendotwill
  • 1,892
  • 18
  • 17
-1

Use this simple code to scroll bottom

 var rows:NSInteger=self.tableName.numberOfRowsInSection(0)
        if(rows > 0)
        {
            let indexPath = NSIndexPath(forRow: rows-1, inSection: 0)
            tableName.scrollToRowAtIndexPath(indexPath , atScrollPosition:  UITableViewScrollPosition.Bottom, animated: true)
        }
            }
Bibin Joseph
  • 234
  • 2
  • 7