我在 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/