首先,請不要告訴我這是重複的。我知道這個問題已經被多次詢問和回答,但即使在閱讀其他人的解決方案之後,我仍然無法讓我的代碼正常工作。UITableViewCell與UILabel子視圖緩存問題
我遇到了一個包含UILabel子視圖的UITableViewCell問題。 UILabel有時不會出現在某些單元格中,直到我從這些單元格滾動並返回給它們。下面是我使用自定義細胞代碼:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *label;
if (cell == nil) {
// cell is nil, create it
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 33)];
label.tag = 888;
} else {
label = (UILabel*)[cell.contentView viewWithTag:888];
[label removeFromSuperview];
}
label.text = @"Label Text";
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
label.center = CGPointMake(cell.contentView.frame.size.width-label.frame.size.width/2-20, cell.contentView.frame.size.height/2);
[cell.contentView addSubview:label];
// customize cell text label
cell.textLabel.text = @"Cell Text";
cell.textLabel.textColor = [UIColor darkGrayColor];
return cell;
}
看來好像標籤正確地顯示出來時dequeueReusableCellWithIdentifier:CellIdentifier返回非零值,但不露面,如果返回值是零和一新單元必須實例化。
如果有人有一個想法,爲什麼這可能會發生,幫助將不勝感激。
嗨,我不明白你爲什麼要創建新的標籤,並插入它們。基本的方法是在編輯器或代碼中準備一個單元格並重用它。雖然重用意味着乾淨和格式化,但不會重新排列甚至找到的單元格。所以對我來說,你似乎在浪費資源。我建議你在編輯板中準備一個自定義單元格,並將其分配給一個類並重用。或者您是否有重新安排標籤的具體原因? – iOS 2012-07-19 21:27:27
我不知道我明白你在說什麼。我正在嘗試向表格單元格的最右側添加一個標籤(與單元格的textLabel屬性分開),並且標籤文本可能會在每次出現表格視圖時更改。 – stackunderflow 2012-07-19 22:12:13