选择UITableViewCell AccessoryView,与选择行分开

时间:2012-08-30 02:49:34

标签: iphone objective-c ios uitableview

我有UITableview我正在显示一些任务,每行都有一个复选框,用于标记任务是否完成。

我希望在用户点击复选框时切换复选标记,并在用户点击该行时切换到详细视图。后者很简单,只需使用

即可
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

但是,我想分开选择区域,仅在选择accessoryview时切换复选框,并仅在选择其余单元格时进入详细视图。如果我在UIbutton内添加了accessoryview,那么当用户只想点击复选框时,用户会选择行和UIButton,对吧?

此外,如果用户只是通过拖动accessoryview来滚动浏览桌面视图,该怎么办?这不会触发TouchUp上UIButton的操作吗?

任何人对如何做到这一点都有任何想法?谢谢你的时间!

1 个答案:

答案 0 :(得分:16)

如何管理此委托方法中的附件点击:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

修改

对于响应accessoryButtonTappedForRowWithIndexPath:方法的自定义accessoryView,您可以执行类似的操作。

cellForRowAtIndexPath:方法 -

BOOL checked = [[item objectForKey:@"checked"] boolValue];
UIImage *image = (checked) ? [UIImage   imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];

[button addTarget:self action:@selector(checkButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;

- (void)checkButtonTapped:(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
{
  NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
  BOOL checked = [[item objectForKey:@"checked"] boolValue];
  [item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];

  UITableViewCell *cell = [item objectForKey:@"cell"];
  UIButton *button = (UIButton *)cell.accessoryView;

  UIImage *newImage = (checked) ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"];
  [button setBackgroundImage:newImage forState:UIControlStateNormal];
}