资源包有10张图片:
sample_pic1.jpg
sample_pic2.jpg
sample_pic3.jpg
...
sample_pic10.jpg
有一个100行的tableView,我想要每10行一个的格式显示上面那10张图片。基本实现了每十行一重复,但是我想要一个重复图片的逻辑方式。
代码:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(@"Inside cellForRowAtIndexPath ... indexPath.row: %d", indexPath.row);
static NSString *CellIdentifier = @"Cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If no cell is available, create a new one using the given identifier.
if (cell == nil)
{
// Use the default cell style.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}//nil-check
int imageCounter = (indexPath.row+1);
//ofcourse this logic doesn't work for rows 21 and up!
if (imageCounter > 10)
{
imageCounter = (indexPath.row+1) - 10;
}
NSLog(@"indexPath.row: %d ... imageCounter: %d ...", indexPath.row, imageCounter);
NSMutableString *tmpImgStr = [NSMutableString stringWithFormat:@"sample_pic%d.jpg", imageCounter];
UIImage *myimage = [UIImage imageNamed:tmpImgStr];
cell.imageView.image = myimage;
}
这里indexPath.row
从0到99。
使用模运算符实现。考虑到从1开始,图片编号也应该从1开始:
int imageCounter = (indexPath.row % 10) + 1;
NSMutableString *tmpImgStr = [NSMutableString stringWithFormat:@"sample_pic%d.jpg", imageCounter];