自定義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. }  
相關文章
相關標籤/搜索