Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dynamically adding of rows when user reached to the last row of the UITableView?

I have a UITableview which shows 10 rows currently which is fixed static. Now I want to add a feature into it. I want to add a more 10 rows to the table when user reach to the last row of the UITableView. I mean currently I am showing fixed 10 rows in the application.

But now I want to add 10 more rows whenever user reaches to the last row of previous UITableview.

Please give me any suggestions or any sample code to achieve my motive. Thanks in advance.

like image 613
Sanchit Paurush Avatar asked Nov 27 '22 03:11

Sanchit Paurush


2 Answers

It is actually quite simple. What you need to do is implement the tableView:willDisplayCell:forRowAtIndexPath: method, which belongs to the UITableViewDelegate protocol. This method hits every time a cell is about to be displayed. So, it will let you know when the last cell is about to be displayed. Then you could do something like-

– (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *) cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{
     if(indexPath.row == [self.array count] - 1) //self.array is the array of items you are displaying
     {
          //If it is the last cell, Add items to your array here & update the table view
     }
}

Another (a bit mathematical) option is to implement UIScrollView delegate methods (UITableView is a subclass of UIScrollView), namely scrollViewDidEndScrollingAnimation: or scrollViewDidScroll:. These will let you know the y-position of the content the user is viewing. If it is found that the bottom most content is visible, you can add more items.

HTH,

Akshay

like image 143
Akshay Avatar answered Nov 30 '22 23:11

Akshay


uitableview is derived from uiscrollview. To achieve your objective, you need to implement scrollViewDidEndDecelerating:

 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float endScrolling = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (endScrolling >= scrollView.contentSize.height) 
    {
      // your code goes here
    }
}

This will detect a "bouncing effect" like shifting up the visible rows to indicate that one would like to see more.

like image 27
yash rathore Avatar answered Dec 01 '22 00:12

yash rathore