我有一个很大的问题。我正在尝试在UITableViewCell
中的每个UITableView
上创建一个收藏按钮。这非常好,我现在有一个动作和选择器按下时执行。
accessory = [UIButton buttonWithType:UIButtonTypeCustom];
[accessory setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
accessory.frame = CGRectMake(0, 0, 15, 15);
accessory.userInteractionEnabled = YES;
[accessory addTarget:self action:@selector(didTapStar) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = accessory;
选择器:
- (void) didTapStar {
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:/* indexPath? */];
accessory = [UIButton buttonWithType:UIButtonTypeCustom];
[accessory setImage:[UIImage imageNamed:@"stared.png"] forState:UIControlStateNormal];
accessory.frame = CGRectMake(0, 0, 26, 26);
accessory.userInteractionEnabled = YES;
[accessory addTarget:self action:@selector(didTapStar) forControlEvents:UIControlEventTouchDown];
newCell.accessoryView = accessory;
}
现在,问题在于:我想知道按下的配件属于哪一行。 我怎么能这样做?
谢谢:)
答案 0 :(得分:20)
我会使用以下代码:
- (void)didTapStar:(id)sender {
NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)[sender superview]];
}
答案 1 :(得分:16)
稍微改变一下你的行动。
- (void)action:(id)sender forEvent:(UIEvent *)event
在该方法中:
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:tableView]];
那应该会得到行的索引路径。
答案 2 :(得分:1)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath {
// To set custom cell accessory
UIImage *image = [UIImage imageNamed:@"white_arrow_right.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(cell.frame.size.width - image.size.width, cell.frame.size.height - image.size.height, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(accessoryButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
}
- (void)accessoryButtonTapped:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil){
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
DetailViewController *detailView =[[DetailViewController alloc]init];
[self.navigationController pushViewController:detailView animated:YES];
}