2012-04-13 65 views
0

我有一個自定義單元格,並在此自定義單元格我有一個按鈕和一個標籤:iOS - 如何在該單元格中處理按鈕事件時訪問自定義單元格?

#import <UIKit/UIKit.h> 

@interface ListCell : UITableViewCell{ 

} 
@property (nonatomic, retain) IBOutlet UIButton* buttonContent; 
@property (nonatomic, retain) IBOutlet UILabel* detailContent; 

@end 

當我處理按鈕的單擊事件:

- (IBAction)expandListCell:(id)sender{ 
    UIButton *button = (UIButton *)sender; 
    ListCell *cell = (ListCell *)button.superview; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    cell.detailContent.text = @"FALSE"; // It throw an exception 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"listCell"; 
    ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    cell.buttonContent.tag = indexPath.row; 
    return cell; 
} 

它拋出一個異常,當我嘗試從我的自定義單元格(ListCell)訪問任何項目:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView detailContent]: unrecognized selector sent to instance 0x8887ca0' 

我想我得到自定義單元格的方式是錯誤的。任何人都知道如何正確地得到它?
預先感謝

+0

請張貼的cellForRowAtIndexPath:太。 – Mat 2012-04-13 09:51:29

+0

問題1:您的自定義單元實現中是否有'@ synthesize'?問題2:你爲什麼要首先獲取單元格 - 你的按鈕應該調用單元格上的方法來告訴它更改文本。您的按鈕代碼不應直接訪問單元格內容。 – 2012-04-13 09:57:39

+0

@Mat:我添加了cellForRowAtIndexPath。尼克布爾:1,是的,我已經合成。 2,當按鈕被點擊時,我確實需要訪問單元格,我發佈的代碼被簡化了 – Dranix 2012-04-13 09:59:05

回答

4

你確定你在調用正確的類嗎? 你確定你的按鈕的超級視圖類是一個ListCell類嗎?

嘗試檢查:

// (...) 
    ListCell *cell = (ListCell *)button.superview; 
    if ([cell.class isSubclassOfClass:[ListCell class]]) { 
     ///// just a check for indexPath: ///// 
     NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
     NSLog(@"current indexPath: %@", indexPath); 
     ///////////// END CHECK /////////////// 
     cell.detailContent.text = @"FALSE"; 
    }else{ 
     NSLog(@"NOT THE RIGHT CLASS!!!"); 
    } 
+1

什麼行**'NSIndexPath * indecPath = [self.tableView indexPathForCell:cell];'** dose there?可能會給出未使用變量索引路徑的警告 – 2012-04-13 09:59:31

+1

@meronix:是的,對,它不是ListCell和UITableViewCell。 ListCell * cell =(ListCell *)button.superview.superview;是獲得細胞的正確方法。謝謝你的回答 – Dranix 2012-04-13 10:07:46

+0

不客氣... – meronix 2012-04-13 10:18:44

1

好,我知道了遺憾沒有得到你的問題正確,你能做的僅僅是一個TEG分配給您的標籤視圖之前將其添加到單元格,然後在retrive的什麼時間只是使用

UILabel *name = (UILabel *)[cell viewWithTag:kLabelTag]; 

並設置標籤的文字

+0

detailContent是一個自定義屬性標籤 – meronix 2012-04-13 09:56:10

+0

可能detailContent是ListCell的一個屬性。 – Mat 2012-04-13 09:57:31

相關問題