ZviBar
ZviBar

Reputation: 10068

UITableViewCell custom accessory button

I use this accessory in cells in a TableView:

cell.accessoryType = UITableViewCellAccessoryDetailButton;

I would like this detail button to look like the clear button in text fields though. How do I do that and still be able to use accessoryButtonTappedForRowWithIndexPath:indexPath method.

Upvotes: 1

Views: 5495

Answers (1)

malex
malex

Reputation: 10096

The only way is to subclass your UITableViewCell. Let it be CustomTableViewCell. Then write the protocol CustomTableViewCell, where define method

@protocol CustomTableViewCellDelegate

- (void)customButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath;

@end

Then define delegate and implement protocol in your YourTableViewController

#import "CustomTableViewCell.h"

@interface YourTableViewController : UITableViewController <CustomTableViewCellDelegate>

@property (nonatomic, weak) id<CustomTableViewCellDelegate> delegate;

..............................

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChatTableViewCellIdentifier forIndexPath:indexPath];

    cell.delegate = self;
    cell.indexPath = indexPath;
    ..........
}

- (void)customButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath
{
    <YOUR_CODE_FOR_PRESS_HANDLER>
}

CustomTableViewCell description:

@protocol CustomTableViewCellDelegate;

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic, strong) NSIndexPath *indexPath;

@end

...................


@implementation CustomTableViewCell

- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

    UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
    yourButton.frame = CGRectMake(0, 0, 25, 25);

    [yourButton.frame setBackgroundImage:[UIImage imageNamed:@"clear_image_name"] forState:UIControlStateNormal];
    [yourButton.frame setBackgroundImage:[UIImage imageNamed:@"clear_image_name_pressed"] forState:UIControlStateHighlighted];

    self.accessoryView = yourButton;
    [yourButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    return self;
}

- (void) buttonPressed:(id)sender
{
    [self.delegate customButtonTappedForRowWithIndexPath:self.indexPath];
}

Upvotes: 3

Related Questions