iphone - 在 1 个单元格内绘制 6 个 ImageView

标签 iphone objective-c core-data uitableview

我有一个非常烦人的问题。我想要做的是将 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/

相关文章:

ios - 如果我强制用户更新到 Appstore 上可用的更新版本,AppStore 会拒绝我的申请吗

iphone - 如何在导航 Controller 之间切换?

iphone - 当目标对象已经为 NULL 时,iOS 如何捕获发送到实例的无法识别的选择器异常?

ios - 我如何在核心数据中保存图像然后检索它?使用 swift

ios - 自动生成的 NSManagedObject 中的属性

iphone - 处理推送通知

iphone - 设备功能编程指南去了哪里?

ios - iOS 应用程序沙箱中的默认文件

ios - 核心数据 - 具有一对多关系的 sectionNameKeyPath

iphone - NSFetchedResultsController 和 executeFetchRequest 之间是否应该存在 UITableView 性能差异?