2011-03-20 57 views
2

我正在制作一个带有表格视图的iPhone应用程序,并且我试图在桌子上的每个单元格旁放置一个不同的图标/图像。从cellForRowAtIndexPath获取单元格编号

我知道你在(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath的代码看起来像这样设置图像:

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

什么我想就是想不通,我怎么针对特定的细胞,所以它有一个独特的形象?像:

if (cell.number == 0) { 
    //Use a specific image 
} 
else if (cell.number == 1) { 
    //Use a different image 

谢谢!

回答

4

indexPath变量包含有关单元位置的信息。修改你的例子:

if (indexPath.row == 0) { 
    // Use a specific image. 
} 

更多信息,请参见NSIndexPath Class ReferenceNSIndexPath UIKit Additions Reference。同样重要的是要注意在每个部分重置单元格编号。

+0

完美更容易,谢谢,我也会阅读苹果的文档。 – rottendevice 2011-03-20 01:11:59

1

使用传递给tableView:cellForRowAtIndexPath:方法的NSIndexPath中的row(也可能是section)属性来标识要查询哪个单元。

0

该函数传递一个索引路径,它具有一个节和一个行。 indexPath.row会传回一个你可以检查的整数。

0

当执行的cellForRowAtIndexPath你可以访问indexPath变量,因此,如果您希望自定义取决于细胞指数单元格样式,你可以做这样的事情:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.row == 0) { 
     // code for cell 0 
    } 
    else { 
     if (indexPath.row == 1) { 
      // code for cell 1 
     } 
    } 
} 

这只是一个例子,我不认为如果使用条件是最好的想法来定制你的单元格,但它会告诉你如何去做你需要的。

请记住,indexPath也包含表的部分。如果您使用分组表格视图,则还需要管理该部分。例如:

if (indexPath.section == 0) { 
    // section 0 
    if (indexPath.row == 0) { 
     // code for section 0 - cell 0 
    } 
    else { 
     if (indexPath.row == 1) { 
      // code for section 0 - cell 1 
     } 
    }   
} 
else { 
    if (indexPath.section == 1) { 
     // section 1 
     if (indexPath.row == 0) { 
      // code for section 1 - cell 0 
     } 
     else { 
      if (indexPath.row == 1) { 
       // code for section 1 - cell 1 
      } 
     } 

    } 
} 
0

一个稍微更好看的方法,我会把所有要使用到一个数组的图片:

_iconArray = @[@"picture1.png", @"picture2.png", @"picture3.png"]; 

这意味着,当你来到cellForRowAtIndex功能,你可以说只有:

cell.imageView.image = [UIImage imageNamed:_iconArray[indexPath.row]]; 

这也是比较容易,如果你有一个以上的部分,这个时候你可以做一个数组的数组,每个都包含了differen所需的图片t部分。

_sectionsArray = @[_iconArray1, _iconArray2, _iconArray3]; 

cell.imageView.image = [UIImage imageNamed:_sectionsArray[indexPath.section][indexPath.row]; 

这立即使得它很容易修改的图片(因为你是只处理阵列。如果你有更多的行和部分(想象做手工为100行)

相关问题