自定义附件视图按钮-选择了错误的行 [英] Custom accessory view button - wrong row selected

查看:50
本文介绍了自定义附件视图按钮-选择了错误的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将UITableViewCell的附件视图实现为按钮,在 按钮的选择器方法,我有以下代码

I have implemented the accessory view of a UITableViewCell as a button, in the button's selector method i have the following code

   - (UIButton *) makeDetailDisclosureButton
   {
       UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
   UIImage* image = [UIImage imageNamed:@"custom.png"];
  [button setImage:image forState:UIControlStateNormal];
  button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);

   [button addTarget: self
           action: @selector(accessoryButtonTapped:withEvent:)
         forControlEvents: UIControlEventTouchUpInside];

      return ( button );
    }


  - (void) accessoryButtonTapped: (UIControl *)button withEvent:(UIEvent *) 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];
  }
}

但是有时选择了错误的行,即如果我点击表中的第0行,我会得到 row = 1实际上被选择.上面的代码是众所周知的解决方案 自定义的附件视图,但事实证明它不可靠.我在这里还需要做些其他事情吗?

However sometimes the wrong row is being selected, ie if I tap on row 0 in the table i get row = 1 actually being selected. The code above is quite well known as a solution for a custom accessory view but it is proving unreliable. Is there something else i need to do here?

推荐答案

尝试一下,

- (void) accessoryButtonTapped: (UIControl *)button withEvent:(UIEvent *) event
{
    UITableViewCell *cell = (UITableViewCell*)button.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}

这里的想法很基本. Button的超级视图应该给我cell.contentView,而它的超级视图是cell.有一个可爱的辅助方法indexPathForCell:,它将为我们提供索引路径,我们可以使用该路径传递给委托方法.

The idea here is pretty basic. Button's superview should give me cell.contentView and it's superview is the cell. There is lovely helper method indexPathForCell: which will give us the index path which we can use to pass to the delegate method.

这篇关于自定义附件视图按钮-选择了错误的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆