1

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.

ZviBar
  • 9,758
  • 6
  • 25
  • 30
  • I found the answer here: http://stackoverflow.com/questions/869421/using-a-custom-image-for-a-uitableviewcells-accessoryview-and-having-it-respond – ZviBar Jan 16 '14 at 21:35

1 Answers1

3

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];
}
malex
  • 9,874
  • 3
  • 56
  • 77
  • I can't see where the button look changes to that of the clear button in the UITextField in this code. – ZviBar Jan 16 '14 at 21:06