用 UISegmentedControl 切換不同的列表頁,往往會對同一個 UITableView 重新 reloadData。如果 cell 裡的子控制項(Label、Button 等)每次都重新建立一次,就會出現同一個 cell 上被層層疊上無數個相同控制件的慘狀——視圖越蓋越厚,記憶體也一路往上衝。
關鍵在於建立子控制項的程式碼寫在了「每次一定會執行」的位置。cell 的建立與子控制項的建立應該綁在一起,只有在真正需要一個全新 cell 的時候才做。
這樣每次進入時會先判斷有沒有可重用的 cell,有就直接取值,沒有才建立,資料與視圖都不會重複堆疊。
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
self.inviteLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, [UIScreen mainScreen].bounds.size.width - 20, 120)];
self.inviteLabel.numberOfLines = 0;
self.inviteLabel.text = cell_info.title;
self.inviteLabel.textColor = LABEL_TEXTCOLOR;
int width = 100;
int height = 40;
self.button = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - width / 2, 120 + 10, width, height)];
self.button.backgroundColor = [UIColor redColor];
[self.button setBackgroundImage:[UIImage imageNamed:cell_info.cp] forState:UIControlStateNormal];
NSLog(@"cell_info.cp:%@", cell_info.cp);
// 加入長按手勢
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPress.minimumPressDuration = 1.0;
[self.inviteLabel addGestureRecognizer:longPress];
[cell.contentView addSubview:self.button];
[cell.contentView addSubview:self.inviteLabel];
cell.backgroundColor = CELL_BACK_COLOR;
}
這個寫法能解決「重複建立」的問題,但上面範例把 inviteLabel、button 存成了 controller 的屬性,多個 cell 時會互相覆蓋,只適合 cell 數量極少或只有單一形態的情況。更嚴謹的做法有兩種:
一是把這些控制件封裝進自訂的 UITableViewCell 子類,在 cell 的初始化方法裡建立一次,再於 cellForRowAtIndexPath: 中只更新文字與圖片;二是註冊 reuseIdentifier 後改用 dequeueReusableCellWithIdentifier:forIndexPath:,並在 prepareForReuse 中清理狀態。
另外,長按手勢若綁在 controller 上,切換資料來源時容易指向錯誤的 cell,建議同樣移進自訂 cell 內處理。