最近在維護一個專案,需要同時兼顧 iOS 5/6 與 iOS 7 上的表視圖行為,過程中遇到兩個相當典型的問題。
查了一輪資料後發現,原因與 iOS 7 的儲存格內部結構調整有關——cell 上多包了一層 scroll view,導致我們直接塞進 contentView 的檢視層級關係不如預期。
下面的寫法未必是最優雅的做法,但確實達到了功能需求。
- (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 是唯讀屬性,別想替換它
// 若 cell 裡沒有 button,直接把要顯示的元件加在 subview 上即可
// 若 cell 裡有 button 且需要各自的事件,則在 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];
// 其他元件可以用 [cell.contentView addSubview:XXX] 加上去
return cell;
}
userInteractionEnabled = NO:這層墊底的容器只是為了整理層級,若讓它參與事件處理,反而會把 cell 本身的點擊事件吃掉。
backgroundColor = clearColor:容器若有不透明背景,會把 cell.backgroundColor 蓋住,讓你以為設定沒有效果。
另外提醒,cell.contentView 是唯讀屬性,無法重新指定,只能透過 addSubview: 往上疊加。若專案已全面採用 iOS 7 以上版本,其實更推薦改用 Auto Layout 或自建 UITableViewCell 子類別,並在 awakeFromNib 中完成版面配置,會比在 cellForRow 中動態拼裝來得穩定。