2015-05-04 41 views
-1

我有一個UITableViewCell裏面有一個按鈕,當我按下按鈕時,它移動到下一個視圖,但我需要傳遞TableViewCell的索引,但我找不到它,因爲它不在DidSelectCellAtIndexPath,它只是可按下的按鈕。在UITableViewCell中的按鈕

如何找出Button的indexPath,以及它爲什麼會崩潰?

+0

添加標籤ti該按鈕並通過該標籤! –

+0

您可以通過使用DidSelectRowAtIndexPath – vijeesh

+0

獲取索引請參閱我的解決方案http://stackoverflow.com/a/22827645/790842。你可以創建'NSIndexPath'作爲屬性,並像在這裏描述的那樣使用它。 – iphonic

回答

0

一個非常簡單的解決方案: -

(void)btnAction:(id)sender 
    CGPoint btnRectPoint = [sender convertPoint:CGPointZero 
            toView:self.tableView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:btnRectPoint]; // Here you can get your indexpath of table 
NSLog(@"index.row=%d",indexPath); 

} 
+0

這工作和日誌的索引路徑,但然後在prepareForSegue,如果我試圖通過indexPath,在ViewController2.h IndexPath它崩潰與「無法識別的選擇器發送到實例」 –

+0

我的代碼在prepareForSegue是 ' - (void )prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { [super prepareForSegue:segue sender:sender]; ViewController2 * view = [segue destinationViewController]; view.indexPath = self.indexPath; }' –

+0

它破壞'view.indexPath = self.indexPath'。 self.indexPath被分配在 - (void)btnAction的底部:(id)sender –

0

您可以創建一個協議,在你UIViewController實現委託方法。現在,當您點擊UITableViewCell中的按鈕時,您可以將單元對象本身作爲參數傳遞給該委託方法。

-(void)protocolMethod:(id)sender { 
    [self.delegate delegateMethod:self]; 
} 

,並在您UIViewController,你可以從你的表視圖獲得該單元的索引路徑。

-(void)delegateMethod:(MyCustomCell*)cell { 
    NSIndexPath *indexPath = [self.objTableView indexPathForCell:cell]; 
}