2012-05-25 29 views
0

我有一個表格視圖,它從網頁中加載信息,並將其顯示在自定義單元格中。在這些自定義單元格中,我有一個通過故事板分配的按鈕。正確地抓取自定義表格單元格中的UIButton的IndexPath.row?

如果按下這個按鈕時,它觸發一個方法(cellForRowAtIndexPath方法中所定義的)

cell.viewArticleButton.action = @selector(viewArticle:); 

正是在這種方法我有麻煩。除了不使用爲每個單元格提供的鏈接(每個索引路徑上的鏈接),而是僅使用第一行的鏈接,而不管我點擊哪一行,該操作的作用不同。

-(IBAction)viewArticle:(id)sender { 

NSLog(@"View Article Button Tapped"); 

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"]; 

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row]; 

    // Open link from item.link 

} 

任何幫助,將不勝感激。我有一種感覺,這是該行沒有做我想要的東西:

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"]; 

回答

0

爲什麼不加添加在NSIndexPath進入方法:

cell.viewArticleButton.action = @selector(viewArticle:indexPath); 

-(IBAction)viewArticle:(id)sender { 
NSIndexPath *indexPath = (NSIndexPath *)sender; 

NSLog(@"View Article Button Tapped for section %d, row $d", indexPath.section, indexPath.row); 

// I have no idea why you are doing this... 
NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"]; 


MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row]; 

    // Open link from item.link 

} 
+0

我試過這個方法,但我不斷收到錯誤:「 - [UIBarButtonItem row]:無法識別的選擇器發送到實例0x3488c0」 – Year3000

+0

沒關係我想通了謝謝。 – Year3000

+0

我怎麼能在Swift中做到這一點? – GJZ

1

這一行:

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"]; 

您正在獲取對原型(或模板)單元格的引用。這不會讓你在你的表格視圖中唯一標識一個單元格。這隻能識別從該原型單元創建的一組單元。這就是你總是獲得第一排的原因;它返回使用此原型創建的第一個單元格。如果您只有一個單元格的標識符爲@"NewsCell"(其他單元格具有不同的標識符),那麼您的實施將起作用。

爲了唯一標識您點擊的單元格,請按照以下主題進行操作:Detecting which UIButton was pressed in a UITableView

相關問題