5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

無限テーブル

Posted at
.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
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?