如何更改tableCell的imageView框架?

时间:2015-10-06 11:05:21

标签: ios objective-c uitableview layout

我想通过目标c代码在每个单元格右侧的UITableViewCell中显示一个imageview。我使用了以下代码但它在左侧显示图像。框架未设置。

UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.size.width/2, 0, cell.frame.size.width/2, cell.frame.size.height)];

       if([[self.categories objectAtIndex:indexPath.section] isKindOfClass:[SpecialPagesCategory class]]) {
           cell.backgroundColor=[UIColor whiteColor];
           bgView.image = [UIImage imageNamed:@"fbBtn.png"];
       } else {
           cell.backgroundColor=[UIColor clearColor];
           bgView.image = nil;
       }

       cell.imageView.image = bgView.image;
       cell.imageView.frame = bgView.frame;

如何通过自定义框架重置UITableViewCell imageView?我正在创建一个像下面这样的单元格

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [self.categoryTable flashScrollIndicators];
        cell.textLabel.font=[UIFont fontWithName:OPEN_SANS size:16.0];
        cell.backgroundColor=[UIColor clearColor]; }

我也曾尝试使用Content View,如下所示

UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.size.width/2, 0, cell.frame.size.width/2, cell.frame.size.height)];
if([[self.categories objectAtIndex:indexPath.section] isKindOfClass:[SpecialPagesCategory class]]) {
           cell.backgroundColor=[UIColor whiteColor];
           bgView.image = [UIImage imageNamed:@"fbBtn.png"];
           [cell.contentView addSubview: bgView];
       } else {
           cell.backgroundColor=[UIColor clearColor];
           bgView.image = nil;
           [cell.contentView addSubview: bgView];
       }

“内容视图”的问题是,对于不满足if条件的单元格,不会删除imageview

2 个答案:

答案 0 :(得分:1)

创建图像视图并将其作为子视图添加到单元格,它将起作用。

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(20, 0, 50, 50)];// Your specification


 imgView.backgroundColor=[UIColor clearColor];
 [imgView.layer setCornerRadius:5.0f];
 [imgView.layer setMasksToBounds:YES];
 [imgView setImage:[UIImage imageWithData: imageData]];
 [  cell.contentView addSubview:imgView];

答案 1 :(得分:1)

覆盖此方法:

- (void)viewWillLayoutSubviews {
   [super viewWillLayoutSubviews];

   [self.myImageView setFrame:CGRectMake(0, 0, 200, 200)];
}

你应该将myImageView替换为图像视图,并设置适当的框架大小。

BTW,代码质量提示:我还建议阅读有关MVC的内容,并将此代码保存在UITableViewCell方法下的layoutSubviews子类实现文件中。