UITableViewCell自定义配件按钮

时间:2014-01-16 20:23:19

标签: ios objective-c cocoa-touch uitableview

我在TableView的单元格中使用此附件:

cell.accessoryType = UITableViewCellAccessoryDetailButton;

我希望这个细节按钮看起来像文本字段中的清除按钮。我该怎么做,仍然可以使用accessoryButtonTappedForRowWithIndexPath:indexPath方法。

1 个答案:

答案 0 :(得分:3)

唯一的方法是将UITableViewCell子类化。让它成为CustomTableViewCell。然后编写协议CustomTableViewCell,其中define方法

@protocol CustomTableViewCellDelegate

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

@end

然后在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说明:

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