iOS 点击UITableViewCell上的控件获取对应的cell

来源:互联网 发布:c51单片机跑马灯程序 编辑:程序博客网 时间:2024/05/22 17:49

场景

很多情况下cell上有很多可以触发的子控件,例如点赞,提示,选择等操作,介绍几个方法,随意感受下

方法1 (获取SuperView)

@implementation UIView (GetCellFromContentviewSubview)- (UITableViewCell *)getCellFromContentviewSubview{    if ([[[self superview] superview] isKindOfClass:[UITableViewCell class]]) {        return (UITableViewCell *)[[self superview] superview];    }    else if ([[[[self superview] superview] superview] isKindOfClass:[UITableViewCell class]]) {        return (UITableViewCell *)[[[self superview] superview] superview];    }    else{         NSLog(@"Something Panic Happens");    }    return nil;}@end

方法2 (另一种方式获取SuperView)

@interface UIView (SuperView)- (UIView *)findSuperViewWithClass:(Class)superViewClass;@end@implementation UIView (SuperView)- (UIView *)findSuperViewWithClass:(Class)superViewClass {    UIView *superView = self.superview;    UIView *foundSuperView = nil;    while (nil != superView && nil == foundSuperView) {        if ([superView isKindOfClass:superViewClass]) {            foundSuperView = superView;        } else {            superView = superView.superview;        }    }    return foundSuperView;}@end// 调用UITableViewCell *cell = [button findSuperViewWithClass:[UITableViewCell class]]

方法3 (墙裂推荐)

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];UITableViewCell *cell = (UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];

这个方法看上去比上面两个舒服多了吧,简单理解下
第一段:指定的控件A,A区域里面的有个坐标(0,0)的位置,把该坐标相对于A控件的位置转换到相对于tableView的坐标
第二段:indexPathForRowAtPoint 根据转换的坐标,获取对应的indexpath
第三段:根据Indexpath获取对应的cell

坐标转换convertPoint非常通俗的讲解,可以加深理解—>传送门

阅读全文
0 0