簡體   English   中英

UITableViewCell自定義配件按鈕

[英]UITableViewCell custom accessory button

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

cell.accessoryType = UITableViewCellAccessoryDetailButton;

我希望這個細節按鈕看起來像文本字段中的清除按鈕。 我該怎么做,仍然能夠使用accessoryButtonTappedForRowWithIndexPath:indexPath方法。

唯一的方法是將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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM