UITableViewCell UITableViewAutomaticDimension prob

2019-07-04 14:34发布

I have an interesting problem. I have a very basic tableview with a bunch of cells of varying height. It's using the iOS 8 UITableViewAutomaticDimension and auto layout constraints.

@interface ViewController () <UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *sentences;
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.sentences = @[
        @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        @"Maecenas consectetur libero viverra sem viverra finibus.",
        @"Nunc arcu orci, pellentesque vel sapien nec, lobortis pulvinar magna"
    ];
    // and a bunch more, see example project

    [self scrollToBottom];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.sentences count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SentenceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.sentence = self.sentences[indexPath.row];
    return cell;
}

- (void)scrollToBottom {
    NSUInteger index = [self.sentences count] - 1;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}

So I want to start scrolled all the way to the bottom, and you have to scroll up to see older stuff. It's for a chat client basically. There are 2 problems: 1, it doesn't actually scroll to the bottom, and 2, when you scroll up, the cells shift position making scrolling jarring and weird. Not smooth at all.

Example project demonstrating the problem: https://github.com/kevinrenskers/AutoHeightFromBottom. Also see https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8/issues/8.

How do I solve this problem? Manually calculate cell height like in the olden days? Switch to collection view? Would that even solve anything?

0条回答
登录 后发表回答