简体   繁体   中英

iOS - Unable to call action from dynamically created button in UITableViewCell

i have created two button programmatically in UITableView
ie Edit Delete

when we click the cell these buttons are displayed but when i try to click in edit or delete button it doesn't calls the appropriate method ie edit or deleteBtn.
This is my code.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"Cell";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell==nil){
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    }

    NSString *cellValue=[firstName objectAtIndex:indexPath.row];
    cell.textLabel.text=cellValue;


    edit=[[UIButton alloc]init];
    [edit setTitle:@"Edit" forState:UIControlStateNormal];
    [edit setFrame:CGRectMake(100, 100, 100, 20)];
    [edit setTag:1];
    [edit addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

    delete=[[UIButton alloc]init];
    [delete setTitle:@"Delete" forState:UIControlStateNormal];
    [delete setFrame:CGRectMake(150, 100, 100, 20)];
    [delete setTag:2];
    [delete addTarget:self action:@selector(deleteBtn) forControlEvents:UIControlEventTouchUpInside];

    [cell.contentView addSubview:delete];
    [cell.contentView addSubview:edit];

    return cell;

}

my edit and delete function are very simple

-(void)edit{

NSLog("%@",selectedValue);
}

-(void)deleteBtn{

NSLog("%@",selectedValue);
}

i have checked this function applying breakpoint but it is not called.

this is how my selectedValue comes

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
selectedValue=[firstName objectAtInder:indexPath.row];
}

Thanks, in advance,
Arun.

please your code like below

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier=@"Cell";

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell==nil){
    cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}

NSString *cellValue=[firstName objectAtIndex:indexPath.row];
cell.textLabel.text=cellValue;


edit=[[UIButton alloc]init];
[edit setTitle:@"Edit" forState:UIControlStateNormal];
[edit setFrame:CGRectMake(100, 5, 100, 20)];
[edit setTag:indexPath.row];
[edit addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:edit];   

delete=[[UIButton alloc]init];
[delete setTitle:@"Delete" forState:UIControlStateNormal];
[delete setFrame:CGRectMake(210, 5, 100, 20)];
[delete setTag:indexPath.row];
[delete addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:delete];

return cell;

}

use methods like below

-(IBAction)edit:(id)sender
{
    int tag = [sender tag];
    NSString *str = [firstName objectAtIndex:tag];
    NSLog("%@",str);
 }

 -(IBAction)deleteBtn:(id)sender
 {
    int tag = [sender tag];
    NSString *str = [firstName objectAtIndex:tag];
    NSLog("%@",str);
 }

Think,the problem is with UIButton frame's. in your code both button's origin.y is 100.0,so it went beyond the cell's bound (Default height is 44.0).

Change your Both UIButton frame like this,and it is worked for me.

UIButton *  edit =[[UIButton alloc]init];
[edit setBackgroundColor:[UIColor blackColor]];
[edit setTitle:@"Edit" forState:UIControlStateNormal];
**[edit setFrame:CGRectMake(100,5.0,100, 30)];**
[edit setTag:1];
[edit addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

UIButton*  delete=[[UIButton alloc]init];
[delete setBackgroundColor:[UIColor blackColor]];
[delete setTitle:@"Delete" forState:UIControlStateNormal];
**[delete setFrame:CGRectMake(200,5.0,100,30)];**
[delete setTag:2];
[delete addTarget:self action:@selector(deleteBtn) forControlEvents:UIControlEventTouchUpInside];

[cell.contentView addSubview:delete];
[cell.contentView addSubview:edit];

Your buttons are being added over and over to the cell because they're being created every time you call CFRAIP. Move them into the cell == nil block:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"Cell";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell==nil){
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
        edit=[UIButton buttonWithType:UIButtonTypeRoundedRect];;
        [edit setTitle:@"Edit" forState:UIControlStateNormal];
        [edit setFrame:CGRectMake(100, 100, 100, 20)];
        [edit setTag:1];
        [edit addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

        delete=[UIButton buttonWithType:UIButtonTypeRoundedRect];;
        [delete setTitle:@"Delete" forState:UIControlStateNormal];
        [delete setFrame:CGRectMake(150, 100, 100, 20)];
        [delete setTag:2];
        [delete addTarget:self action:@selector(deleteBtn) forControlEvents:UIControlEventTouchUpInside];

        [cell.contentView addSubview:delete];
        [cell.contentView addSubview:edit];
    }

    NSString *cellValue=[firstName objectAtIndex:indexPath.row];
    cell.textLabel.text=cellValue;
    return cell;

}

The problem is in the setFrame

The height of the table cell is less than the co-ordinates you have set for the buttons. Change the code to

[edit setFrame:CGRectMake(100, 5, 100, 20)]; 

and this will work.

OR

just increase the height of the table rows, which by default is 44 , using

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

Please try to use this one ....and do same thing for delete button ..........

if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

        // -------------------- Add button to cell --------------
        edit = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 20)];

        [edit setTitle:@"Edit" forState:UIControlStateNormal];
        [edit setTag:1];
        [edit addTarget:self action:@selector(edit)   forControlEvents:UIControlEventTouchUpInside];        

        [cell.contentView addSubview:edit];
    }

请更改按钮名称,因为编辑和删除已在Objective C中定义了关键字

I can you try to custom cell and can you add buttons in custom cell view and implement below codes.

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

    static NSString *CellIdentifier = @"Cell";

    cell = [self.tbl dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {


        //****cell recent deal buy button click goes to login or check out pageview 
        //[cell.btn setTag:indexPath.row];
        //[cell.btn addTarget:self action:@selector(buybutton_checkout:)
       //   forControlEvents:UIControlEventTouchDown];
       // cell.btn.hidden=NO;


        NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"icel" owner:nil options:nil];

        for (UIView *view in views)
        {
            if([view isKindOfClass:[UITableViewCell class]])
            {

                cell = (icel*)view;

            }

        }
    }

   //tbl.layer.cornerRadius = 3.9;
    //[tbl setClipsToBounds:YES];


    [cell.activity startAnimating]; 

    [cell.btn setTitle:_BUYNOW_BTN forState:UIControlStateNormal];
    [cell.btn setTag:indexPath.row];
    [cell.btn addTarget:self action:@selector(Buy_btnlck:)
                forControlEvents:UIControlEventTouchDown];
        //cell.btn.hidden=NO;
    cell.title_lbl.text=[[_today_similardeal_title_ary objectAtIndex:indexPath.row]capitalizedString];


        index_tbl=indexPath.row;
    return cell;
    }
}
-(IBAction)Buy_btnlck:(UIButton *)button
{
NSInteger intvalue=[[NSString stringWithFormat:@"%ld",(long int)[button tag]]intValue];
}

Modify your code as like this....

Replace the below two lines...

edit=[[UIButton alloc] init];
delete=[[UIButton alloc] init];

as like this...

UIButton *edit = [UIButton buttonWithType:UIButtonTypeRoundedRect];

UIButton *delete=[UIButton buttonWithType:UIButtonTypeRoundedRect]];

Don't use [UIButton alloc] init] . Use instead this

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(edit:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Edit" forState:UIControlStateNormal];
 button.frame = CGRectMake(80.0, 21.0, 40.0, 40.0);
[view addSubview:button];

Where view is the view where you are adding your button as a subview. you can also set Button frame according to your requirements.

Try this::

Table Method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // Configure the cell.
   UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

   if(cell==nil){
      cell= [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier] autorelease];

      NSString *cellValue=[firstName objectAtIndex:indexPath.row];
      cell.textLabel.text=cellValue;

      UIButton *btnEdit=[UIButton buttonWithType:UIButtonTypeCustom];
      [btnEdit setTitle:@"Edit" forState:UIControlStateNormal];
      [btnEdit setFrame:CGRectMake(100, 100, 100, 20)];
      [btnEdit setTag:indexPath.row];
      [btnEdit addTarget:self action:@selector(clickEdit:) forControlEvents:UIControlEventTouchUpInside];

      [cell.contentView addSubview:btnEdit];


      UIButton *btnDelete=[UIButton buttonWithType:UIButtonTypeCustom];
      [btnDelete setTitle:@"Delete" forState:UIControlStateNormal];
      [btnDelete setFrame:CGRectMake(150, 100, 100, 20)];
      [btnDelete setTag:indexPath.row];
      [btnDelete addTarget:self action:@selector(clickDelete:) forControlEvents:UIControlEventTouchUpInside];

      [cell.contentView addSubview:btnDelete];
   }
   return cell;
}

Then, Button Action Methods

-(IBAction)clickEdit:(id)sender
{
   NSString *str = [firstName objectAtIndex:[sender tag]];
   NSLog("Name :: %@",str);
}

-(IBAction)clickDelete:(id)sender
{
   NSString *str = [firstName objectAtIndex:[sender tag]];
   NSLog("Name :: %@",str);
}

Hopefully, it'll help you.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM