Jon Wells
Jon Wells

Reputation: 4259

Add a Button to a TableView Cell:

I have a UI tableView and I am trying to create a button like the one used in the Safari Settings to Clear History:

enter image description here

The code I have tried doesnt really work and I'm sure there is a better way:

        case(2):
           // cell = [[[ButtonLikeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


            if (indexPath.row == 0) 
            {            
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setFrame:cell.bounds]; 
                [button addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside];
                [button setBackgroundColor:[UIColor purpleColor]];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitle:@"Clear Data" forState:UIControlStateNormal];
                cell.accessoryView = nil;
                cell.clipsToBounds=YES;
                [cell.contentView addSubview:button];
            }

            break;
    }
}

return(cell);

}

Upvotes: 1

Views: 1883

Answers (2)

wattson12
wattson12

Reputation: 11174

A subclass on the tableview cell is overkill for this, basically all you need to do is set the text alignment of the textLabel to center

case(2):
        if (indexPath.row == 0) 
        {   
            cell.textLabel.textAlignment = UITextAlignmentCenter;
        }
        break;

Upvotes: 4

Jorge Cohen
Jorge Cohen

Reputation: 1522

no need to use an actual UIButton.

the only difference between does rows and "normal" rows is the position of the label. subclass UITableViewCell and override -laysubviews to center the label and you're done, like so:

@interface ButtonLikeCell : UITableViewCell

@end

@implementation ButtonLikeCell

-(void)layoutSubviews
{
    self.titleLabel.center = self.center;
}

@end

this will reposition the label of the cell and make it look similar to what you're looking for.

Upvotes: 2

Related Questions