iOS: 获取UITableViewCell上添加的子控件对应的cell

时间:2022-07-19 10:37:25

一、简单介绍

UITableViewCell是UITableView的核心部分,我们在开发中因为功能的扩展经常需要自定义,以便在其上面添加子控件,例如button、label等。添加后获取这些子控件的cell,因为iOS不同系统的缘故此处会有一个坑,可能会崩溃。接下来以button为例来解决。

二、崩溃情况

  • 在自定义cell的时候,在cell上添加了一个button,然后在controller中调用这个button的时候要获取到cell,在iOS6中直接button.superView就可以。
  • 但是iOS7中不行,发现iOS7第一次的superview只能取到cell的contentView,也就说得取两次,但是结果发现还是不行,取两次竟然才取到cell的contentView层,不得已取三次superview实现。
  • 但是更新iOS8之后的调用发现崩溃···检查发现三次取superview竟然取多了,到tableview层上了。也就是说iOS8就是得取两次。

三、superView正确取法

iOS6取一次superview就行,也即 button.superView
iOS7取三次superview,也即 button.superView.superView.superView
iOS8取两次superview,也即 button.superView.superView

CustomCell *cell = nil;
if (IsIOS7) {
UIView *view = [btn superview];
UIView *view2;
if (IsIOS8) {
view2 = view;
}else{
view2 = [view superview];
}
cell = (CustomCell *)[view2 superview];
}else{
cell = (CustomCell *)[btn superview];
}

四、其他做法

(上面通过superView取太麻烦了,还要照顾其他系统,下面的这些方法是相当理想的,推荐使用)

1、通过代理方法

/**
代理方法
@param btn cell中的按钮
@param cell cell
*/
-(void)didClickButton:(UIButton *)btn InCell:(UITableViewCell *)cell;

2、通过block回调

/**
点击cell上按钮的block回调
@param buttonCallBlock 回调
*/
-(void)didClickButtonCallBlock:(void (^)(UIButton *btn,UITableViewCell *cell))buttonCallBlock;

3、通过标记button的tag,使其等于cell的indexPath.row+100,然后通过[tableView cellForRowAtIndexPath: indexpath]获取

/** 
获取cell
*/

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_btn.tag-100 inSection:0];

UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];

4、通过触摸点touch转换point坐标获取

/**
点击事件
*/
[cell.btn addTarget:self action:@selector(cellBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside]; /**
通过点击按钮的触摸点转换为tableView上的点,然后根据这个点获取cell
*/
- (void)cellBtnClicked:(id)sender event:(id)event
{
NSSet *touches =[event allTouches];
UITouch *touch =[touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:_tableView];
NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
if (indexPath!= nil)
{
UITableViewCell *cell = [_tableView cellForRowAtIndexPath: indexPath];
}
}