關于uitableviewcell的accessoryType屬性

使用的話,例如:


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 *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;

//在這里加入自己的邏輯

??

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容