一、简单介绍
UITableViewCell是UITableView的核心部分,我们在开发中因为功能的扩展经常需要自定义,以便在其上面添加子控件,例如button、label等。添加后获取这些子控件的cell,因为iOS不同系统的缘故此处会有一个坑,可能会崩溃。接下来以button为例来解决。
二、崩溃情况
三、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]; } }
iOS: 获取UITableViewCell上添加的子控件对应的cell
原文:http://www.cnblogs.com/XYQ-208910/p/6663677.html