資源包有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];