在iPhone应用程序中从自定义单元格中调用方法



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

我在该视图控制器中具有表视图。在我的表视图中,我加载一个自定义单元格。在我的自定义单元格中,有1个标签和1个按钮。我设置了FirstVc的自定义单元格的标签和按钮。请参阅Bellow代码。

在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 从自定义单元格中。但是这个想法是行不通的。请建议我新想法。

     - (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;

}

最新更新