2011-03-20 73 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行)