根据TableViewCell的subviews得到对应的TableViewCell以及NSIndexPath


============================================================
博文原创,转载请声明出处
============================================================


在升级项目到ios8,对于TableViewCell比较崩溃,应为ios6,7,8,的TableViewCell结构都不相同


For iOS >= 8:

       NSLog(@"%@",[[sender superview] class]);   //UITableViewCell
       NSLog(@"%@",[[[sender superview] superview] class]); //UITableViewWrapperView
       NSLog(@"%@",[[[[sender superview]superview]superview] class]);  //UITableView


For iOS >= 7 && <8:

       NSLog(@"%@",[[sender superview] class]);   //UITableViewCellContentView
       NSLog(@"%@",[[[sender superview] superview] class]); //UITableViewCellScrollView
       NSLog(@"%@",[[[[sender superview]superview]superview] class]);  //UITableViewCell

For iOS <7:

       NSLog(@"%@",[[sender superview] class]);   //UITableViewCellContentView
       NSLog(@"%@",[[[sender superview] superview] class]); //UITableViewCell
       NSLog(@"%@",[[[[sender superview]superview]superview] class]);  //UITableView



总之给我的感觉就是乱起八糟,各种判断,这里介绍一种简单的方法。

CGRect senderFrame = [sender convertRect:sender.bounds toView:self.table];
NSIndexPath *indexPath = [self.table indexPathForRowAtPoint: senderFrame.origin];
UITableViewCell *cell=[self.table cellForRowAtIndexPath:indexPath];


因为这个经常调用,我写成了宏

#define INDEXPATH_SUBVIEW_TABLEVIEW(subview,tableview)\
({\
CGRect subviewFrame = [subview convertRect:subview.bounds toView:tableview];\
NSIndexPath *indexPath = [tableview indexPathForRowAtPoint:subviewFrame.origin];\
indexPath;\
})\

#define CELL_SUBVIEW_TABLEVIEW(subview,tableview)\
({\
CGRect subviewFrame = [subview convertRect:subview.bounds toView:tableview];\
NSIndexPath *indexPath = [tableview indexPathForRowAtPoint:subviewFrame.origin];\
UITableViewCell *cell=[_tvItems cellForRowAtIndexPath:indexPath];\
cell;\
})\




也可以使用下面方法

    UIView *view = sender;
    while (view && ![sender isKindOfClass:[UITableViewCell class]]){
        view = view.superview;
    }
    UITableViewCell *cell=(UITableViewCell*)view;

不过个人觉得如果程序有问题,会造成死循环。。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值