对于 UItableVIEwCell 而言,其 accessoryType属性有4种取值:
UItableVIEwCellAccessoryNone,
UItableVIEwCellAccessorydisclosureIndicatorUItableVIEwCellAccessoryDetaildisclosurebuttonUItableVIEwCellAccessorycheckmark
分别显示 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 {
}
这样,当 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;
//在这里加入自己的逻辑
⋯⋯
}
总结以上是内存溢出为你收集整理的自定义 UITableViewCell 的 accessory 样式全部内容,希望文章能够帮你解决自定义 UITableViewCell 的 accessory 样式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)