最近在維護一個同時要跑在 iOS 5/6 與 iOS 7 上的專案,遇到兩個現象:cell 裡的內容顯示不出來,cell 內的按鈕也點不動。查了資料才知道,iOS 7 的 cell 內部多包了一層 scrollView,導致原本的 hit-test 行為改變。
下面的寫法不一定最優雅,但確實達到了功能要求:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *subview = [[[UIView alloc] init] autorelease];
subview.userInteractionEnabled = NO; // 設為 NO 才不會屏蔽 cell 的點擊事件
subview.backgroundColor = [UIColor clearColor]; // 設為透明,讓 cell.backgroundColor 生效
subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:subview]; // contentView 是 readonly,別想替換它
// ...
return cell;
}
兩個設定各有其必要性:userInteractionEnabled = NO 讓觸摸事件穿透,cell 本身的 didSelectRow 才收得到;背景設為透明,是為了不遮蓋 cell 自己的背景色。
直接在 subview 上加要顯示的控件就好。
把 subview 建立好之後,圖片與其他裝飾放進 subview,功能性控件則加在 cell.contentView 上:
UIView *subview = [[[UIView alloc] init] autorelease]; subview.userInteractionEnabled = NO; subview.backgroundColor = [UIColor clearColor]; subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:subview]; UIImageView *imagess = [[UIImageView alloc] init]; imagess.frame = CGRectMake(0, 0, 320, lblContents.frame.size.height + 45); // 圖片自適應高度 [imagess setImage:[UIImage imageNamed:@"xq_sonactivity_list.png"]]; [subview addSubview:imagess]; // 其他需要互動的控件直接加在 contentView 上 [cell.contentView addSubview:myButton];
iOS 7 之後 UITableViewCell 的內容層級結構被調整,直接往 cell 上加子檢視時,觸摸事件的 hit-test 路徑可能落在系統插入的中間層上,於是 cell 選取與內部控件的事件都會失效。把裝飾性內容集中到一個不接收觸摸的容器裡,讓互動性控件留在 contentView 上,是相容性最好的折衷做法。
另外,這個範例是 MRC 寫法。若要在新專案使用,記得改用 ARC,並以 dequeueReusableCellWithIdentifier: 搭配 cellForRowAtIndexPath: 版本,避免 cell 重用時子檢視不斷堆疊。