(0066)iOS開發(fā)之UITableViewCell上子控件通過superView找對應(yīng)的cell的探究

轉(zhuǎn)載自:http://www.cnblogs.com/XYQ-208910/p/6663677.html

一、簡單介紹
UITableViewCell是UITableView的核心部分,我們在開發(fā)中因?yàn)楣δ艿臄U(kuò)展經(jīng)常需要自定義,以便在其上面添加子控件,例如button、label等。添加后獲取這些子控件的cell,因?yàn)閕OS不同系統(tǒng)的緣故此處會有一個坑,可能會崩潰。接下來以button為例來解決。

二、崩潰情況
在自定義cell的時(shí)候,在cell上添加了一個button,然后在controller中調(diào)用這個button的時(shí)候要獲取到cell,在iOS6中直接button.superView就可以。
但是iOS7中不行,發(fā)現(xiàn)iOS7第一次的superview只能取到cell的contentView,也就說得取兩次,但是結(jié)果發(fā)現(xiàn)還是不行,取兩次竟然才取到cell的contentView層,不得已取三次superview實(shí)現(xiàn)。
但是更新iOS8之后的調(diào)用發(fā)現(xiàn)崩潰···檢查發(fā)現(xiàn)三次取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取太麻煩了,還要照顧其他系統(tǒng),下面的這些方法是相當(dāng)理想的,推薦使用)
1、通過代理方法

/**
代理方法
@param btn cell中的按鈕
@param cell cell
*/
-(void)didClickButton:(UIButton *)btn InCell:(UITableViewCell *)cell;

2、通過block回調(diào)

/**
點(diǎn)擊cell上按鈕的block回調(diào)
@param buttonCallBlock 回調(diào)
*/
-(void)didClickButtonCallBlock:(void (^)(UIButton *btn,UITableViewCell *cell))buttonCallBlock;

3、通過標(biāo)記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、通過觸摸點(diǎn)touch轉(zhuǎn)換point坐標(biāo)獲取

/**
點(diǎn)擊事件
*/
[cell.btn addTarget:self action:@selector(cellBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];

/**
通過點(diǎn)擊按鈕的觸摸點(diǎn)轉(zhuǎn)換為tableView上的點(diǎn),然后根據(jù)這個點(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];
    }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容