2011-08-24 113 views
19

我有一個UITableView從服務器獲取的信息和對數據發佈到一個表視圖。每個單元格的內部都是來自服務器的信息。編程圖像添加到細胞的TableView

對於這個例子的目的,假設我們從服務器獲得的信息是數字:1,2,3,4

我想要做的就是添加圖像(編程,因爲有如果涉及等),以左側的細胞的,和文本(1,2,等語句)它旁邊。

基本上,我想每個單元看起來像這樣:

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

請原諒我的粗例證。 :)

回答

19

在這裏你去:

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

斯威夫特:

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

這個問題應該被定格在我在2015年9月24日編輯答案。 –

3

的UITableViewCell對象有一個imageView財產;你可以設置此圖像視圖的形象,它會自動在標題旁邊正確的位置顯示圖像。

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 Programming Guide

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; 
} 
5

第一個答案的雨燕2.0的版本是:

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