简体   繁体   中英

Scroll to bottom in UITableView

I have a chatScreen built using UITableView . I want to scroll to bottom of UITableView , the moment the screen is opened from some other view controller.However using trivial scroll to bottom functions, shows a jerk if the chat is long.Is there an alternative?

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSIndexPath* lastIndexPath = [NSIndexPath indexPathForRow:_messagesArray.count-1  inSection:0];
        [_tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    });
}

使用UITableViewScrollPositionBottom代替UITableViewScrollPositionTop

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat height = _tableView.contentSize.height - _tableView.bounds.size.height;
        [_tableView setContentOffset:CGPointMake(0, height) animated:YES];  
    });
}

I think this is what you want:

extension UITableView {

    func scrollToBottom() {
        scrollToRow(at: IndexPath(row: numberOfRows(inSection: numberOfSections-1)-1, section: numberOfSections-1),
                    at: .bottom, animated: true)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM