从iphone应用程序中的自定义单元调用方法

时间:2012-11-03 07:56:43

标签: iphone uibutton custom-cell

我有一个视图控制器
姓名:FirstVC

我在该视图控制器中有表视图。在我的表视图中,我加载自定义单元格。在我的自定义单元格中有1个标签和1个按钮。我从FirstVC设置标签以及定制单元的按钮。见下文代码。

在FirstVC.h中

@interface FirstVC : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
    IBOutlet UITableView *TblView;
    IBOutlet CustomCell *customCell;
}
- (void)addCounter:(NSInteger)pCat_ID;

@end
在FirstVC.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *cellIdentifier = @"Cell";
        CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if(cell == nil){
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell_iPhone" owner:self options:nil];
            cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell = categoryCustomCell;
        }
NSInteger pCat_id = [[[arrayCategoryData objectAtIndex:indexPath.row] objectForKey:@"cat_id"] integerValue];
        [customCell setTextForLable:@"Test"];
        [customCell setAddCounterButton:pCat_id];

        return cell;
}

- (void)addCounter:(NSInteger)pCat_ID
{
    //Some code here….
}
在CustomCell.h中

@interface CustomCell : UITableViewCell
{
    IBOutlet UILabel *lblCategoryName;
    IBOutlet UIButton *btnAddCounter;
}

- (void)setTextForLable:(NSString *)cat_name;
- (void)setAddCounterButton:(NSInteger)cat_ID;

@end
CustomCell.m中的

@implementation CustomCell

- (void)setTextForLable:(NSString *)cat_name
{
    lblCategoryName.text = cat_name;
}

- (void)setAddCounterButton:(NSInteger)cat_ID
{
    [btnAddCounter addTarget:self action:@selector(addCounter:cat_ID) forControlEvents:UIControlEventTouchUpInside];
}

@end

我想从自定义单元格调用 addCounter:(NSInteger)pCat_ID 方法。但这个想法无法奏效。请建议我新的想法。

1 个答案:

答案 0 :(得分:3)

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier = @"Cell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil){
    [[NSBundle mainBundle] loadNibNamed:@"CustomCell_iPhone" owner:self options:nil];
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell = categoryCustomCell;
    } 
     NSInteger pCat_id = [[[arrayCategoryData objectAtIndex:indexPath.row] 
    // call your method from here.. and put your method in this file then it will work for you
 [cell.btnAddCounter addTarget:self action:@selector(addCounter:pCat_id) forControlEvents:UIControlEventTouchUpInside];

    return cell;

}