iOS: 獲取UITableViewCell上添加的子控件對應的cell


一、簡單介紹

UITableViewCell是UITableView的核心部分,我們在開發中因為功能的擴展經常需要自定義,以便在其上面添加子控件,例如button、label等。添加后獲取這些子控件的cell,因為iOS不同系統的緣故此處會有一個坑,可能會崩潰。接下來以button為例來解決。

 

二、崩潰情況

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

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];
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM