UITableview的每个单元格中的不同图像

utt*_*tam 3 iphone objective-c uitableview uiimage

我想为表格视图的每个单元格设置不同的图像.我不知道怎么做 - 请帮帮我.

Ste*_*son 9

  1. 创建一个属性来存储不同图像名称的数组.

    在header(.h)文件中:

    @interface MyViewController : UITableViewController {
        NSArray *cellIconNames;
        // Other instance variables...
    }
    @property (nonatomic, retain) NSArray *cellIconNames;
    // Other properties & method declarations...
    @end
    
    Run Code Online (Sandbox Code Playgroud)

    在您的implementation(.m)文件中:

    @implementation MyViewController
    @synthesize cellIconNames;
    // Other implementation code...
    @end
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在您的viewDidLoad方法中,将该cellIconNames属性设置为包含不同图像名称的数组(按其要显示的顺序):

    [self setCellIconNames:[NSArray arrayWithObjects:@"Lake.png", @"Tree.png", @"Water.png", @"Sky.png", @"Cat.png", nil]];
    
    Run Code Online (Sandbox Code Playgroud)
  3. tableView:cellForRowAtIndexPath:表视图数据源方法中,获取与单元格行对应的图像名称:

    NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
    
    Run Code Online (Sandbox Code Playgroud)

    然后创建一个UIImage对象(cellIconName用于指定图像)并将单元格设置imageView为此UIImage对象:

    UIImage *cellIcon = [UIImage imageNamed:cellIconName];
    [[cell imageView] setImage:cellIcon];
    
    Run Code Online (Sandbox Code Playgroud)

在第3步之后,您的tableView:cellForRowAtIndexPath:方法将如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /* Initialise the cell */

    static NSString *CellIdentifier = @"MyTableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    /* Configure the cell */

    NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
    UIImage *cellIcon = [UIImage imageNamed:cellIconName];
    [[cell imageView] setImage:cellIcon];

    // Other cell configuration code...

    return cell;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ong 5

您可以在其中创建包含UIImageView的自定义单元格,但最简单的方法是在-cellForRowAtIndexPath表视图委托中设置默认UITableViewCell的内置图像视图.像这样的东西:

UITableViewCell *cell = [tableView 
                              dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
    //... other cell initializations here
}

[[cell imageView] setImage:image];
Run Code Online (Sandbox Code Playgroud)

其中image是通过从URL或本地应用程序包加载而创建的UIImage.