iOS UITableView Scroll to bottom of section

前端 未结 5 434
鱼传尺愫
鱼传尺愫 2021-01-01 23:48

I am going to make a tableview with 2 sections inside it. I can add cells to every section programmatically and when i add, i scroll to the end of tableview using



        
相关标签:
5条回答
  • 2021-01-02 00:22

    Just in case, this is solution in Swift:

    extension UITableView {
        func scrollToBottom(animated: Bool = true) {
            let sections = self.numberOfSections
            let rows = self.numberOfRowsInSection(sections - 1)
            self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
        }
    }
    
    0 讨论(0)
  • 2021-01-02 00:29

    In Swift 3 it's been updated to:

    let indexPath = IndexPath(row: self.numberOfRowsInSection(0) - 1), section: 0)
    self.commentsTableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
    
    0 讨论(0)
  • 2021-01-02 00:32

    when you inserting row at end you have its index path, you can use scrollToIndexPath method of tableview to scroll

    [self.liveChannelsTable scrollToRowAtIndexPath:IndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    0 讨论(0)
  • 2021-01-02 00:38

    All the suggestions above are correct, at least based on the docs. But it did not work in my case - I could not get the scroll to show the last row in the table view. I had to add a delay in scrolling to make that work.

    - (void)scrollToTheBottom:(BOOL)animated
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
    

    I called the above as:

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self scrollToTheBottom:YES];
    });
    
    0 讨论(0)
  • 2021-01-02 00:40

    You can try with this code:

    int yourSection = 2;
    int lastRow = [tableView numberOfRowsInSection:yourSection] - 1;
    [tableView scrollToRowAtIndexPath:[NSIndexPath lastRow inSection:yourSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    

    You get the numbers of rows in your section, then scroll to that indexPath.

    0 讨论(0)
提交回复
热议问题