我有一个非常烦人的问题。我想要做的是将 6 个 ImageView 绘制到一个单元格中。在下面的屏幕上您会看到我想要实现的目标。
这就是我在 cellForRowAtIndexPath 中所做的事情
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
for(int i=0;i<5;i++)
{
float xCoord = 30.0;
Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:team.image]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
UIImageView* imgView = [[UIImageView alloc] initWithImage:image];
[imgView setFrame:CGRectMake(xCoord,0,66,66)];
[cell.contentView addSubview:imgView];
xCoord += imgView.frame.size.width + 5;
NSLog(@"%f",xCoord);
[cell.contentView clearsContextBeforeDrawing];
}
return cell;
}
有人可以帮我吗?
最佳答案
即使您通过计算 x
修复了错误坐标在每次迭代中重置回 30,您将遇到重用单元格的问题:您的程序添加了新的 UIImageView
s 到单元格,即使它可能包含五个 UIImageView
对象已经。经过几轮重用后,单元格中将有几十个图像彼此重叠,这对性能产生灾难性影响 - 尤其是滚动性能。
您应该定义 UITableViewCell
的自定义子类有六个UIImageView
作为 subview 添加的对象,给它一个像这样的方法
-(void)setImage:(UIImage*)image forPosition:(NSUInteger)position;
并在循环中调用此方法(如果您想要六个图像,则循环应将 i <= 5
而不是 i < 5
作为其结束条件)。
编辑:这是一种过于简单的编码方法:
CustomCell.h:
#define NUM_PICS 6
@interface SixPicsCell : UITableViewCell {
UIImageView *pics[NUM_PICS];
}
-(void)setImage:(UIImage*)image forPosition:(NSUInteger)position;
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
@end
CustomCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
for (int i = 0 ; i != NUM_PICS ; i++) {
pics[i] = [[UIImageView alloc] initWithImage:nil];
[pics[i] setFrame:CGRectMake(30+71*i, 0, 66, 66)];
[self.contentView addSubview:pics[i]];
}
}
return self;
}
-(void)setImage:(UIImage*)image forPosition:(NSUInteger)position {
pics[position].image = image;
}
关于iphone - 在 1 个单元格内绘制 6 个 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12816919/