2013-03-10 175 views
2

使用UICollectionView,我試圖添加另一個UICollectionViewCell。這第一個代碼顯示第一個單元格,它運行良好。當我試圖添加另一個UICollectionViewCell時會出現問題。UICollectionView - 多個不同的單元格

static NSString *identifier = @"Cell"; // Default Cells 

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; 
UIImageView *illustrationImage = (UIImageView *)[cell viewWithTag:100]; 
illustrationImage.image = [UIImage imageNamed:[stackImage objectAtIndex:indexPath.row]]; 

UILabel *stackLabel = (UILabel *)[cell viewWithTag:12]; 
[stackLabel setText:[stackTitle objectAtIndex:indexPath.row]]; 

在這裏,我想添加一個全新的細胞,具有不同的內容,我UICollectionView。每當我運行此代碼,整個事情拒絕推出:

static NSString *newIdentifier = @"AddNewCell"; 

UICollectionViewCell *newCell = [collectionView dequeueReusableCellWithReuseIdentifier:newIdentifier forIndexPath:indexPath]; 

UIImageView *addNewImage = (UIImageView *)[newCell viewWithTag:120]; 
addNewImage.image = [UIImage imageNamed:[addNew objectAtIndex:indexPath.row]]; // This line makes the app crash 

return cell; 
return newCell; 

錯誤消息

終止應用程序由於未捕獲的異常 'NSRangeException',原因是:「* - [__ NSArrayI objectAtIndex :]:index 1 beyond bounds [0..0]'

我懷疑這與indexPath.row有關。 如果我替換下面的代碼與indexPath.row部分「0」,那麼它不會崩潰,但它UICollectionView將不可見:

[addNew objectAtIndex:indexPath.row]] 

回答

3

首先,我假設你正在運行您在 collectionView中提供的代碼片段:cellForItemAtIndexPath:方法,而不是代碼中的其他位置。

另外,您不能在所述方法內一次創建(也不返回!!)兩個單元格。你應該根據收到的索引路徑作爲參數來決定你出隊,實例化和返回的單元格。現在

,關於「超越界限指數」錯誤您收到:你想訪問你要訪問它叫做addNew數組這是不是目前在陣列中實際存在的元素。在你的情況下,你嘗試訪問數組的第二個元素(索引1),並且該數組只有一個元素(索引0)。

您可能想驗證addNew陣列已正確初始化之前您正在訪問它

相關問題