我想将NSMutableArray
中的图片添加到tableview中的自定义单元格。每个单元格中将有四个或更多图像。所以这是我的问题:
如果我引用indexPath.row
,自定义单元格将如下所示:
cell1:picture1,picture2,picture3,picture4
cell2:picture2,picture3,picture4,picture5
cell3:picture3,picture4,picture5,picture6
但我想:
cell1:picture1,picture2,picture3,picture4
cell2:picture5,picture6,picture7,picture8
cell3:picture9,picture10,picture11,picture12
我是xCode的新手,我看不到一个好的解决方案。
代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"ImageCustomCell";
ImageCustomCell *cell = (ImageCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ImageCustomCell" owner:nil options:nil];
for(id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (ImageCustomCell *) currentObject;
break;
}
}
}
// here i get the indexPath.row for every cell and add +1 - +3 to it to get the next image, but every new cell just get +1, not +4
cell.imageForCell.image = [UIImage imageWithContentsOfFile:[imagePathArray objectAtIndex:indexPath.row]];
cell.imageForCell2.image = [UIImage imageWithContentsOfFile:[imagePathArray objectAtIndex:indexPath.row+1]];
cell.imageForCell3.image = [UIImage imageWithContentsOfFile:[imagePathArray objectAtIndex:indexPath.row+2]];
cell.imageForCell4.image = [UIImage imageWithContentsOfFile:[imagePathArray objectAtIndex:indexPath.row+3]];
return cell;
}
答案 0 :(得分:1)
你的问题是indexPath.row
每次调用tableView:cellForRowAtIndexPath:
时增加一个,你编码好像它增加了4个。当然,UITableView
行索引增量应该并且将保留在每行一个,所以你必须找到一个不同的方法。
您需要找到一个函数,将indexPath
映射到imagePathArray
中与您想要放置在indexPath
所描述的行的单元格中最左侧的图像对应的索引。一旦找到该索引,剩下的三个图像就只有1个,2个和3个元素偏移。
由于这不是标记为“家庭作业”,我想我只会给你答案:它是行乘以每行的图像数量。您可以随意使用它,也可以使用这段代码。尚未编译或测试,如果您无法解决任何错别字或错误,请告诉我。
实施这样的方法:
- (NSArray *)imagePathsForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger imagePathArrayStartingIndex = indexPath.row * IMAGES_PER_ROW;
NSRange imagePathArrayIndexRange = NSMakeRange(imagePathArrayStartingIndex, IMAGES_PER_ROW);
NSIndexSet *imagePathArrayIndexes = [NSIndexSet indexSetWithIndexesInRange:imagePathArrayIndexRange];
NSArray *imagePathsForRow = [imagePathArray objectsAtIndexes:imagePathArrayIndexes];
return imagePathsForRow;
}
然后在tableView:cellForRowAtIndexPath
:
NSArray *imagePathsForRow = [self imagePathsForRowAtIndexPath:indexPath];
cell.imageForCell.image = [UIImage imageWithContentsOfFile:[imagePathsForRow objectAtIndex:0]];
cell.imageForCell2.image = [UIImage imageWithContentsOfFile:[imagePathsForRow objectAtIndex:1]];
cell.imageForCell3.image = [UIImage imageWithContentsOfFile:[imagePathsForRow objectAtIndex:2]];
cell.imageForCell4.image = [UIImage imageWithContentsOfFile:[imagePathsForRow objectAtIndex:3]];
希望这有帮助!