.h
# import <UIKit/UIKit.h>
@interface InfiniteTableView : UITableView
<UITableViewDataSource>
@end
.m
# import "InfiniteTableView.h"
@interface InfiniteTableView() {
int mTotalCellsVisible;
}
@end
@implementation InfiniteTableView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.showsVerticalScrollIndicator = NO;
}
return self;
}
-(void)resetContentOffsetIfNeeded {
NSArray *indexpaths = [self indexPathsForVisibleRows];
int totalVisibleCells = indexpaths.count;
if( mTotalCellsVisible > totalVisibleCells )
{
//we dont have enough content to generate scroll
return;
}
CGPoint contentOffset = self.contentOffset;
//check the top condition
//check if the scroll view reached its top.. if so.. move it to center.. remember center is the start of the data repeating for 2nd time.
if( contentOffset.y <= 0.0) {
contentOffset.y = self.contentSize.height / 3.0f;
}
else if( contentOffset.y >= ( self.contentSize.height - self.bounds.size.height) )//scrollview content offset reached bottom minus the height of the tableview
{
//this scenario is same as the data repeating for 2nd time minus the height of the table view
contentOffset.y = self.contentSize.height/3.0f- self.bounds.size.height;
}
[self setContentOffset: contentOffset];
}
- (void)layoutSubviews
{
[super layoutSubviews];
mTotalCellsVisible = self.frame.size.height / self.rowHeight;
[self resetContentOffsetIfNeeded];
}
-(NSInteger)numberOfSectionsInTableView: (UITableView *)tableView {return 1;}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return 10 * 3;}
-(UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellid = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
}
cell.textLabel.text = [NSString stringWithFormat:@"cell: %d", indexPath.row % 10];
return cell;
}
@end