UITableViewCell的accessoryType属性

使用的话,例如:app

cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式  框架

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头,距离右边有十几像素;  ide

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;//cell右边有一个蓝色的圆形button;  spa

cell.accessoryType = UITableViewCellAccessoryCheckmark;//cell右边的形状是对号;  
orm


对于 UITableViewCell 而言,其 accessoryType属性有4种取值:
对象

UITableViewCellAccessoryNone,索引

UITableViewCellAccessoryDisclosureIndicator,事件

UITableViewCellAccessoryDetailDisclosureButton,get

UITableViewCellAccessoryCheckmarkit

分别显示 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;

//在这里加入本身的逻辑

⋯⋯

}

相关文章
相关标签/搜索