2013-05-08 99 views
0

在我的項目中,我有自定義UITableview單元,其中恰好有一個按鈕。當這個按鈕被選中時,它會觸發一個繼續。在此segue中,我將一個對象從單元傳遞到目標UIViewcontroller。我目前使用下面的代碼故事板自定義UITableviewcell選擇

else if ([[segue identifier] isEqualToString:@"Add"]) 
{ 
    SearchAddRecordViewController *addRecordViewController = [segue destinationViewController]; 
    NSIndexPath *path = [self.tableView indexPathForSelectedRow]; 
    SearchCell *cell = [self.tableView cellForRowAtIndexPath:path]; 
    NSLog(@"%@", cell.record); 
    addRecordViewController.workingRecord = cell.record; 
} 

原來我路過空,因爲按鈕沒有觸發細胞的選擇,因此沒有indexPathForSelectedRow。我的問題是,如何獲得按下按鈕的單元格的索引路徑。

編輯: 回答

回答

0

對於任何遇到類似問題的人來說,這就是我能夠解決這個問題的方法。

我首先創建了具有NSIndexPath屬性的UIButton子類的實現和頭文件。我將故事板中的uibutton分配給這個具有NSIndexPath屬性的新定製解除按鈕的超類。添加以下代碼到SEGUE識別步驟(密鑰被實現我可以使用發送者對象作爲觸發SEGUE的來源):

else if ([[segue identifier] isEqualToString:@"Add"]) 
{ 
    SearchAddRecordViewController *addRecordViewController = [segue destinationViewController]; 
    addRecordButton *button = (addRecordButton*) sender; 
    NSIndexPath *path = button.indexPath; 
    SearchCell *cell = [self.tableView cellForRowAtIndexPath:path]; 
    addRecordViewController.workingRecord = cell.record; 
} 
0

你在你的自定義單元格的.h文件中聲明一個變量NSIndexpath並指定indexPath到的cellForRowAtIndexPath該變量。並檢索它並使用它....希望它能工作

+0

這將如何幫助我?問題是我無法從按鈕訪問單元格。按鈕會觸發segue,也許我可以在按鈕上使用某種標籤?我不知道如何使用Storyboard製作動態標籤,儘管 – dkirlin 2013-05-08 07:31:14

0

的另一種方式,以確定避免子類的UIButton將是indexPath :

CGPoint point = [button.superview convertPoint:button.center toView:self.tableView]; 
NSIndexPath *path = [self.tableView indexPathForRowAtPoint:point]; 

編輯:

我分解成一個不錯的方法,這一點,你可以添加到一個類別上的UITableView:

-(NSIndexPath*)indexPathOfCellComponent:(UIView*)component { 
    if([component isDescendantOfView:self] && component != self) { 
     CGPoint point = [component.superview convertPoint:component.center toView:self]; 
     return [self indexPathForRowAtPoint:point]; 
    } 
    else { 
     return nil; 
    } 
} 
+0

這給了我表格下一個單元格的索引路徑。他們是否會減少獲得適當的路徑? – dkirlin 2013-05-09 00:59:10

+0

對不起,代碼是不正確的,我現在糾正它。 'convertPoint'顯然需要在'button.superview'上調用,而不是直接在按鈕上調用! – 2013-05-09 09:20:19

0

您可以按以下方式做到這一點,這可以幫助你唯一標識哪個按鈕被竊聽,你可以通過適當的值,我只是傳遞一個字符串值,例如

假設OutputString是一個字符串物業在您的目的地視圖控制器

if ([[segue identifier] isEqualToString:@"yourSegueIdentifier"]) { 

    UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview]; 
    NSIndexPath *clickedButtonPath = [self.myTableView indexPathForCell:clickedCell]; 
    [segue.destinationViewController setOutputString:@"XYZ"];   
} 
+0

這對UITableViewCell中的視圖層次結構做了一些假設,但這可能並非如此。使用'indexPathForRowAtPoint:'查看我的答案以獲得更健壯的方法。 – 2013-05-08 11:05:48