以编程方式将图像添加到表视图单元格

23

我有一个UITableView,从服务器获取信息并将数据发布到表格视图中。每个单元格内都包含来自服务器的信息。

为了举例说明,假设我们从服务器获得的信息是数字:1、2、3、4。

我想要做的是在单元格的左侧添加一张图片(由于涉及if语句等,需要通过编程实现),并将文本(1、2等)放在其旁边。

基本上,我希望每个单元格看起来都像这样:

 _____________________________________
| (IMAGE) (TEXT)                      | --CELL 0
--------------------------------------
 _____________________________________
| (IMAGE) 2                           | --CELL 1
--------------------------------------

请原谅我粗糙的插图。 :)

5个回答

21

给你:

cell.imageView.image = [UIImage imageNamed:@"image.png"];

Swift:

cell.imageView?.image = UIImage(named: "image.png")

那个问题应该在我于2015年9月24日编辑答案时得到修复。 - meh-uk

8
您可以在UITableViewController子类中像这样将图像和文本都添加到UITableViewCell中:
- (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] autorelease];
    }

    [[cell imageView] setImage:anImage];
    [[cell textLabel] setText:[NSString stringWithFormat:@"%d",[indexPath row]];

     return cell;
}

UITableViewCell有一些内置属性,您可以利用它们,例如imageView、textLabel和detailTextLabel。如需更多信息,请查看Table View编程指南


5

第一个答案的Swift 2.0版本如下:

cell.imageView?.image = UIImage(named: "image.png")

4

UITableViewCell对象拥有一个imageView属性;你只需要设置这个图像视图的图像,就能自动显示在正确的位置,并且标题会显示在旁边。


0
// create a rectangle box for image view

UIImageView *iconImage = [[UIImageView alloc] init];
iconImage.frame = CGRectMake(12,4,53.5,53.5);

// Create a label for cells
UILabel *cellName = [[UILabel alloc] initWithFrame:CGRectMake(75,18,200,20)];
cellName.font = [self fontForBodyTextStyle];

NSString *cellNameStr = [NSString stringWithFormat:@"%@",self.tableCellNames[indexPath.row]];

// Select path row tab actions
switch (indexPath.row) {
    case 0:

        cellName.text = cellNameStr;
        iconImage.image = [UIImage imageNamed:@"condition.png"];
        [cell.contentView addSubview:iconImage];
        [cell.contentView addSubview:cellName];

        break;

    case 1:
       cellName.text = cellNameStr;
        iconImage.image = [UIImage imageNamed:@"videos.png"];
        [cell.contentView addSubview:iconImage];
        [cell.contentView addSubview:cellName];
        break;

    case 2:
        cellName.text = cellNameStr;
        iconImage.image = [UIImage imageNamed:@"provider.png"];
        [cell.contentView addSubview:iconImage];
        [cell.contentView addSubview:cellName];
        break;

    case 3:
        cellName.text = cellNameStr;
        iconImage.image = [UIImage imageNamed:@"info.png"];
        [cell.contentView addSubview:iconImage];
        [cell.contentView addSubview:cellName];
        break;

    default:
        NSAssert(NO, @"Unhandled value in cellForRowAtIndexPath");
        break;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接