ysnky
ysnky

Reputation: 458

Adding button into UITableViewCell

I am trying to add button into my table cell like below:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 ....
 UIButton* buttonCheckbox = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonCheckbox.frame = CGRectMake(0, 177, 56, 26);
        buttonCheckbox.backgroundColor = [UIColor redColor];
        [buttonCheckbox addTarget:self action:@selector(actionFirst1) forControlEvents:UIControlEventTouchUpInside];


        [buttonCheckbox setTitle:@"MyTitle" forState:UIControlStateNormal];

        [cell addSubview:buttonCheckbox];

but actionFirst1 event is not fired. if i add the button [self.view addSubview:buttonCheckbox] instead of [cell addSubview:buttonCheckbox] it works fine. why?

thanks...

Upvotes: 1

Views: 1889

Answers (3)

Suraj Mirajkar
Suraj Mirajkar

Reputation: 1391

Hi try below code it may help you out:

if ([indexPath row] == 0) 
    {
                  UIButton *myButton = [[UISwitch alloc]initWithFrame:CGRectMake(x, y, width, 
                                        heigth)];
        [cell addSubview:myButton];
        cell.accessoryView = myButton;
        [myButton addTarget:self action:@selector (actionFirst1) 
                                  forControlEvents:UIControlEventTouchUpInside];
           }

This code will help you out. Please set frames according to your cell of TableView.

Upvotes: 1

Joe Strout
Joe Strout

Reputation: 2741

Please see whether it would suffice to add your button as the accessoryView of the table cell. In that case, the iOS framework will position the button in the right place for your cell style itself (though you still need to give it a size). Here's an example from one of my projects:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(0, 0, 100, 27);  // only size matters
[myButton setTitle:@"Connect" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(connect:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = myButton;

That's it. You just create the control, make sure it has a size, and set it to the accessoryView.

Upvotes: 1

Felipe Sabino
Felipe Sabino

Reputation: 18205

You should add this button to the contentView property of your cell

[cell.contentView addSubview:buttonCheckbox];

In fact, all your custom elements inside a UITableViewCell should be placed inside the contentView as this cell elements (contentView, accessorView and image) are all placed on top of any elements that your cell have.

Check this doc for more info on cell about custom UITableviewCell

Upvotes: 2

Related Questions