自定义UITableViewCell的accessory样式

自定义UITableViewCell的accessory样式
      默认的accessoryType属性有四种取值:UITableViewCellAccessoryNone、 UITableViewCellAccessoryDisclosureIndicator、 UITableViewCellAccessoryDetailDisclosureButton、 UITableViewCellAccessoryCheckmark。
若是想使用自定义附件按钮的其余样式,则需使用UITableView的 accessoryView属性来指定。
[cpp]  view plain copy
  1. UIButton *button;  
  2. if(isEditableOrNot) {  
  3.     UIImage *p_w_picpath = [UIImage p_w_picpathNamed:@"delete.png"];  
  4.     button = [UIButton buttonWithType:UIButtonTypeCustom];  
  5.     CGRect frame = CGRectMake(0.0,0.0,p_w_picpath.size.width,p_w_picpath.size.height);  
  6.     button.frame = frame;  
  7.     [button setBackgroundImage:p_w_picpath forState:UIControlStateNormal];  
  8.     button.backgroundColor = [UIColor clearColor];  
  9.     cell.accessoryView = button;  
  10. }else{  
  11.     button = [UIButton buttonWithType:UIButtonTypeCustom];  
  12.     button.backgroundColor = [UIColor clearColor];  
  13.     cell.accessoryView = button;  
  14. }  
以上代码仅仅是定义了附件按钮两种状态下的样式,问题是如今这个自定义附件按钮的事件仍不可用。
即事件还没法传递到 UITableViewDelegate的accessoryButtonTappedForRowWithIndexPath方法上。
当咱们在上述代码 中在加入如下语句:
        [button addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
后, 虽然能够捕捉到每一个附件按钮的点击事件,但咱们还没法进行区别究竟是哪一行的附件按钮发生了点击动做!由于addTarget:方法最多容许传递两个参 数:target和event,这两个参数都有各自的用途了(target指向事件委托对象,event指向所发生的事件)。看来只依靠Cocoa框架已 经没法作到了。
      但咱们仍是能够利用event参数,在自定义的btnClicked方法中判断出事件发生在UITableView的哪个cell上。由于UITableView有一个很关键的方法 indexPathForRowAtPoint,能够根据触摸发生的位置,返回触摸发生在哪个cell的indexPath。并且经过event对象,正好也能够得到每一个触摸在视图中的位置。
 
[cpp]  view plain copy
  1. // 检查用户点击按钮时的位置,并转发事件到对应的accessory tapped事件  
  2. - (void)btnClicked:(id)sender event:(id)event  
  3. {  
  4.      NSSet *touches = [event allTouches];  
  5.      UITouch *touch = [touches anyObject];  
  6.      CGPoint currentTouchPosition = [touch locationInView:self.tableView];  
  7.      NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];  
  8.      if(indexPath != nil)  
  9.      {  
  10.          [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];  
  11.      }  
  12. }  
 
这样, UITableView的accessoryButtonTappedForRowWithIndexPath方法会被触发,而且得到一个indexPath参数。经过这个indexPath参数,咱们便可区分到底哪一行的附件按钮发生了触摸事件。
[cpp]  view plain copy
  1. - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     int  *idx = indexPath.row;  
  4.    //这里加入本身的逻辑  
  5. }  
相关文章
相关标签/搜索