轉(zhuǎn)載自:http://www.cnblogs.com/XYQ-208910/p/6663677.html
一拳缠、簡(jiǎn)單介紹
UITableViewCell是UITableView的核心部分,我們?cè)陂_(kāi)發(fā)中因?yàn)楣δ艿臄U(kuò)展經(jīng)常需要自定義,以便在其上面添加子控件,例如button、label等。添加后獲取這些子控件的cell,因?yàn)閕OS不同系統(tǒng)的緣故此處會(huì)有一個(gè)坑疫诽,可能會(huì)崩潰。接下來(lái)以button為例來(lái)解決旦委。
二奇徒、崩潰情況
在自定義cell的時(shí)候,在cell上添加了一個(gè)button社证,然后在controller中調(diào)用這個(gè)button的時(shí)候要獲取到cell逼龟,在iOS6中直接button.superView就可以。
但是iOS7中不行追葡,發(fā)現(xiàn)iOS7第一次的superview只能取到cell的contentView腺律,也就說(shuō)得取兩次奕短,但是結(jié)果發(fā)現(xiàn)還是不行,取兩次竟然才取到cell的contentView層匀钧,不得已取三次superview實(shí)現(xiàn)翎碑。
但是更新iOS8之后的調(diào)用發(fā)現(xiàn)崩潰···檢查發(fā)現(xiàn)三次取superview竟然取多了,到tableview層上了之斯。也就是說(shuō)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];
}
四、其他做法
(上面通過(guò)superView取太麻煩了瘫絮,還要照顧其他系統(tǒng)涨冀,下面的這些方法是相當(dāng)理想的,推薦使用)
1麦萤、通過(guò)代理方法
/**
代理方法
@param btn cell中的按鈕
@param cell cell
*/
-(void)didClickButton:(UIButton *)btn InCell:(UITableViewCell *)cell;
2鹿鳖、通過(guò)block回調(diào)
/**
點(diǎn)擊cell上按鈕的block回調(diào)
@param buttonCallBlock 回調(diào)
*/
-(void)didClickButtonCallBlock:(void (^)(UIButton *btn,UITableViewCell *cell))buttonCallBlock;
3、通過(guò)標(biāo)記button的tag壮莹,使其等于cell的indexPath.row+100翅帜,然后通過(guò)[tableView cellForRowAtIndexPath: indexpath]獲取
/**
獲取cell
*/
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_btn.tag-100 inSection:0];
UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
4、通過(guò)觸摸點(diǎn)touch轉(zhuǎn)換point坐標(biāo)獲取
/**
點(diǎn)擊事件
*/
[cell.btn addTarget:self action:@selector(cellBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
/**
通過(guò)點(diǎn)擊按鈕的觸摸點(diǎn)轉(zhuǎn)換為tableView上的點(diǎn)命满,然后根據(jù)這個(gè)點(diǎn)獲取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];
}
}