您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 7 中 UITableViewCell 內容不顯示、按鈕無回應的解法

編輯:iOS 相關資訊

最近在維護一個專案,需要同時兼顧 iOS 5/6 與 iOS 7 上的表視圖行為,過程中遇到兩個相當典型的問題。

問題描述

  • iOS 7 上儲存格裡的內容顯示不出來。
  • 儲存格中的 UIButton 點下去沒有任何反應。

查了一輪資料後發現,原因與 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 中動態拼裝來得穩定。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved