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

一、简单介绍

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];
    }
}

 

转载于:https://www.cnblogs.com/XYQ-208910/p/6663677.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值