2014-01-30 34 views
0

我在我的UITableView上顯示2個自定義單元格。我展示他們像這樣:索引超出UITableView與2個自定義單元

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"StepsViewCell"; 
    static NSString *simpleTableIdentifier2 = @"descViewCell"; 

    if(indexPath.row == 0) { 
     UITableViewCell *cell = nil; 
     cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier2]; 
     if(!cell) { 
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"descViewCell" owner:self options:nil]; 
       cell = [nib objectAtIndex:0]; 
      } 
      cell.textLabel.text = [descLabel objectAtIndex:indexPath.row]; 

      return cell; 
    } 
     else { 
      StepViewCell *cell = nil; 
      cell = (StepViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
      if(!cell) { 
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StepsViewCell" owner:self options:nil]; 
       cell = [nib objectAtIndex:0]; 
      } 

      cell.stepTextLbl.text = [stepLabel objectAtIndex:indexPath.row]; 
      [cell.thumbImage setImage:[UIImage imageNamed: @"full_breakfast.jpg"] forState:UIControlStateNormal]; 

      return cell; 
      } 
     } 

我使用下面的代碼descViewCell始終爲1

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return [stepLabel count] +1; 
} 

這工作計數他們,但是我得到index (5) beyond bounds (5)當我向下滾動至底部的UITableView和它崩潰。我究竟做錯了什麼?

回答

4

這是因爲在- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section中,您將爲返回的結果加1。所以你的stepLabel數組有5個元素(索引0-4)。但是當你給這個數字加1時,你的代碼就會認爲你有6行,它們在索引0-5處。所以你的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法試圖從只有5個元素的數組的索引5訪問數據(因此,結束於索引4)。

你可以做如下修改代碼來解決這個崩潰:

cell.stepTextLbl.text = [stepLabel objectAtIndex:indexPath.row-1]; 

我認爲這將完成你想要的東西,因爲它看起來像它只是進入你的這部分代碼,如果該行是大於0,所以這1降檔的值,這樣你所訪問從0與索引您的陣列 - 4

1

stepLabel數爲5 numberOfRowsInSection:返回6.這條線:

cell.stepTextLbl.text = [stepLabel objectAtIndex:indexPath.row]; 

當indexPath.row = 5時,會因爲沒有stepLabel [5]而導致應用程序崩潰。嘗試使用

cell.stepTextLbl.text = [stepLabel objectAtIndex:(indexPath.row - 1)];