我正在做一个学生项目,我需要知道点击了哪一行中的哪个按钮。
每一行都有不同的标签,一个喜欢按钮和一个不喜欢按钮。
我确实知道如何使用 NSIndexPath.row 来检测按下了哪一行,但在这种情况下,我需要知道哪一行以及该行中的哪个按钮被按下。
我已经在整个 SO 中搜索了一个很好的解决方案,以检测在每行有多个按钮时单击按钮的哪一行。
根据我阅读其他帖子的理解,使用 button.tag 可能非常难以预测,因此如果可能,我宁愿使用不同的方法。
我见过很多应用程序都实现了这个,所以必须有一个最佳的方法来做到这一点。有人有什么好的建议吗?
代码:
搜索单元.h
@interface SearchCell : UITableViewCell {
IBOutlet UIButton *likebutton2;
IBOutlet UIButton *dislikebutton2;
}
@property (nonatomic,retain) IBOutlet UILabel *track_label;
@property (nonatomic,retain) IBOutlet UILabel *artist_label;
@property (nonatomic,retain) IBOutlet UILabel *album_label;
@property (nonatomic,retain) IBOutlet UIButton *likebutton2;
@property (nonatomic,retain) IBOutlet UIButton *dislikebutton2;
@property (nonatomic, copy) void (^onButton)(UIButton *button);
- (void)buttonAction:(UIButton *)sender;
@end
搜索细胞.m
#import "SearchCell.h"
#import "RootViewController.h"
@implementation SearchCell
@synthesize likebutton2, dislikebutton2, track_label, artist_label, album_label;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code.
}
return self;
}
- (void)buttonAction:(UIButton *)sender
{
self.onButton(sender);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state.
}
- (void)dealloc {
[super dealloc];
}
@end
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *uniqueIdentifier = @"searchCell";
SearchCell *cell = nil;
Search *currentSearch = nil;
cell = (SearchCell *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
if (tableView == [[self searchDisplayController] searchResultsTableView]) //Just from some previous debugging
{
currentSearch = [[searchxmlParser searchhits] objectAtIndex:indexPath.row];
}
if(!cell)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[SearchCell class]]) {
cell = (SearchCell *)currentObject;
[cell.likebutton2 addTarget:cell action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.dislikebutton2 addTarget:cell action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
cell.likebutton2.tag = 1;
cell.dislikebutton2.tag = 2;
break;
}
}
}
cell.onButton = ^(UIButton *theButton) {
[self handleButton:theButton indexPath:indexPath];
}
cell.track_label.text = [currentSearch track];
cell.artist_label.text = [currentSearch artist];
return cell;
}
谢谢你的帮忙 :)!