轉載自:http://blog.csdn.net/kmyhy/article/details/6442351
使用的話,例如:
[cpp]view plaincopy
- cell.accessoryType = UITableViewCellAccessoryNone;//cell沒有任何的樣式
- cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右邊有一個小箭頭,距離右邊有十幾像素;
- cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;//cell右邊有一個藍色的圓形button;
- cell.accessoryType = UITableViewCellAccessoryCheckmark;//cell右邊的形狀是對号;
對于 UITableViewCell 而言,其 accessoryType屬性有4種取值:
UITableViewCellAccessoryNone,
UITableViewCellAccessoryDisclosureIndicator,
UITableViewCellAccessoryDetailDisclosureButton,
UITableViewCellAccessoryCheckmark
分别顯示 UITableViewCell 附加按鈕的4種樣式:
無、、、。
除此之外,如果你想使用自定義附件按鈕的其他樣式,必需使用UITableView 的 accessoryView 屬性。比如,我們想自定義一個
的附件按鈕,你可以這樣做:
UIButton *button ;
if(isEditableOrNot){
UIImage *p_w_picpath= [UIImage p_w_picpathNamed:@"delete.png"];
button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, p_w_picpath.size.width, p_w_picpath.size.height);
button.frame = frame;
[button setBackgroundImage:p_w_picpathforState:UIControlStateNormal];
button.backgroundColor= [UIColor clearColor];
cell.accessoryView= button;
}else {
}
這樣,當 isEditableOrNot 變量為 YES 時,顯示如下視圖:
但仍然還存在一個問題,附件按鈕的事件不可用。即事件無法傳遞到 UITableViewDelegate 的accessoryButtonTappedForRowWithIndexPath 方法。
也許你會說,我們可以給 UIButton 加上一個 target。
好,讓我們來看看行不行。在上面的代碼中加入:
[button addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
然後實作btnClicked方法,随便在其中添加點什麼。
點選每個 UIButton,btnClicked 方法中的代碼被調用了!一切都是那麼完美。
但問題在于,每個 UITableViewCell 都有一個附件按鈕,在點選某個按鈕時,我們無法知道到底是哪一個按鈕發生了點選動作!因為addTarget 方法無法讓我們傳遞一個差別按鈕們的參數,比如 indexPath.row 或者别的什麼對象。addTarget 方法最多允許傳遞兩個參數:target和 event,而我們确實也這麼做了。但這兩個參數都有各自的用途,target 指向事件委托對象——這裡我們把 self 即 UIViewController執行個體傳遞給它,event 指向所發生的事件比如一個單獨的觸摸或多個觸摸。我們需要額外的參數來傳遞按鈕所屬的 UITableViewCell 或者行索引,但很遺憾,隻依靠Cocoa 架構,我們無法做到。
但我們可以利用 event 參數,在 btnClicked 方法中判斷出事件發生在UITableView的哪一個 cell 上。因為 UITableView 有一個很關鍵的方法 indexPathForRowAtPoint,可以根據觸摸發生的位置,傳回觸摸發生在哪一個 cell 的indexPath。 而且通過 event 對象,我們也可以獲得每個觸摸在視圖中的位置:
// 檢查使用者點選按鈕時的位置,并轉發事件到對應的accessorytapped事件
- (void)btnClicked:(id)senderevent:(id)event
{
NSSet *touches =[event allTouches];
UITouch *touch =[touches anyObject];
CGPointcurrentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
if (indexPath!= nil)
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
這樣,UITableView的accessoryButtonTappedForRowWithIndexPath方法會被觸發,并且獲得一個indexPath 參數。通過這個indexPath 參數,我們可以區分到底是衆多按鈕中的哪一個附件按鈕發生了觸摸事件:
-(void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath{
int* idx= indexPath.row;
//在這裡加入自己的邏輯