简体   繁体   中英

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.

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];
}

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