2012-10-06 34 views
5

當使用UICollectionView時,我很困惑獲取didSelectItemAtIndexPath方法的indexPath值。indexPath UICollectionView的值

我使用下面的代碼行中didSelectItemAtIndexPath方法:

//FileList is an NSArray of files from the Documents Folder within my app. 
//This line gets the indexPath of the selected item and finds the same index in the Array 
NSString *selectedItem = [NSString stringWithFormat:@"%@",[FileList objectAtIndex:indexPath.item]]; 

//Now the selected file name is displayed using NSLog 
NSLog(@"Selected File: %@", selectedItem); 

的問題是,所述indexPath總是返回0(見下面的代碼),結果僅在第一項FileList NSArray被選中。

我已經嘗試了不同的參數,如

  • indexPath.row
  • indexPath.item
  • ,只是普通的indexPath

所有的這些在下面的NSLog語句返回值0:

NSLog(@"index path: %d", indexPath.item); //I also tried indexPath.row here 

也許我只是格式化NSString不正確,但我不認爲這是事實,因爲沒有任何警告,我試圖在其他地方以不同的格式。

爲什麼indexPath始終返回0?

任何幫助,將不勝感激!謝謝!

+1

請說明如何格式化'NSLog'的字符串 – dasblinkenlight

+0

'.item'在這裏是合適的屬性,但功能上與'.row'沒有什麼不同。你需要展示更多 - 你怎麼知道它是零?什麼是FileList? – jrturton

+0

我編輯了這個問題,包括了我如何格式化NSLog字符串,並且我已經闡明瞭FileList是什麼(請閱讀註釋代碼) –

回答

1

您使用的代理方法始終提供所選單元格的索引路徑。 嘗試使用NSLog調用中的斷點進行調試。當調試器停止時,查看底部的調試區域並使用控制檯(如果需要,可使用視圖=>調試區域=>激活控制檯)。

鍵入控制檯:po indexPath

您應該看到這樣的事情,如果選擇的產品列表中的第5號:0(第一部分和可能是唯一一個)

<NSIndexPath 0xa8a6050> 2 indexes [0, 5]

希望這有助於弄清楚發生了什麼。

30

在陳述明顯的風險時,請確保您的代碼位於didSelectItemAtIndexPath方法中,而不是didDeselectItemAtIndexPath。在後一種方法中,對於給定的觸摸事件,您將獲得非常不同的indexPath值,並且使用Xcode的代碼完成時插入錯誤的值非常容易。

+2

夥計,你救了我。我正在調試一個小時,謝謝。 –

+2

現在我抓了兩次。 Grrr ... – malaki1974

+2

該死的你,自動完成 – DaGaMs