ios - UITableViewCell 自定义附件按钮

标签 ios objective-c cocoa-touch uitableview

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

cell.accessoryType = UITableViewCellAccessoryDetailButton;

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

最佳答案

唯一的方法是继承你的 UITableViewCell。让它成为CustomTableViewCell。然后编写协议(protocol)CustomTableViewCell,其中define方法

@protocol CustomTableViewCellDelegate

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

@end

然后在 YourTableViewController 中定义委托(delegate)和实现协议(protocol)
#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];
}

关于ios - UITableViewCell 自定义附件按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21172097/

相关文章:

ios - 子类 UITextField 默认在开头添加空格

ios - 如何测试 Google Analytics iOS 应用程序安装

ios - 使用 NSURLSession 的 SFTP 不工作

ios - Fabric - 无法完成设置下载

objective-c - 如果比较两个 NSString 对象时 "a == b"为假

ios - 用于 View 数组的自动布局可视化编程语言

ios - Objective-C 中的参数化 SQLite 查询

ios - Swift - 必须调用父类(super class) SKSpriteNode 错误的指定初始值设定项

iphone - 尝试从XCode [iOS 5.0.1]运行应用程序时,检测到与已安装的库AFTER INSTALLING SPIRE的UUID不匹配

objective-c - 格式化字符串中的值以具有小数点分隔符