對於 UITableViewCell 而言,其 accessoryType屬性有4種取值:
UITableViewCellAccessoryNone,
UITableViewCellAccessoryDisclosureIndicator,
UITableViewCellAccessoryDetailDisclosureButton,
UITableViewCellAccessoryCheckmark
分別顯示 UITableViewCell 附加按鈕的4種樣式:
無、、、。
除此之外,如果你想使用自定義附件按鈕的其他樣式,必需使用UITableView 的 accessoryView 屬性。比如,我們想自定義一個
的附件按鈕,你可以這樣做:
UIButton *button ;
if(isEditableOrNot){
UIImage *image= [UIImage imageNamed:@"delete.png"];
button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:imageforState:UIControlStateNormal];
button.backgroundColor= [UIColor clearColor];
cell.accessoryView= button;
}else {
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor= [UIColor clearColor];
cell.accessoryView= button;
}
這樣,當 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;
//在這裏加入自己的邏輯
⋯⋯
}