[英]Repeat Problem of tableview cell during scrolling in iphone
有5個單元格,每個單元格都有一個動態標簽。 單元格的高度是使用heightForRowAtIndexPath方法根據標簽內容定義的。 現在,正在顯示3個單元格。 當我滾動到下一個單元格時,一次調用cellForRowAtIndexPath,然后在輸出中正確顯示一個(4或5)單元格,但另一個單元格具有第一個單元格內容(重復)。 有解決此問題的解決方案嗎? cellForRowAtIndexPath方法應被調用2次。 我已經正確定義了部分和行。
取消判斷
如果(cell == nil)
很好。我現在解決我的問題。非常感謝。
您可能沒有正確重用單元格。 滾動時, UITableView
會重用上一個單元格,但不會正確更改其內容。
cellForRowAtIndexPath
的代碼應類似於以下內容:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = @"CustomCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];
}
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];
return cell;
}
你看起來像這樣嗎?
永遠不要刪除if(cell == nil)
。
而是清除在單元格上添加的子視圖。
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}else{
NSArray *cellSubviews= [cell.contentView cellSubviews];
for (UIView * view in subviews) {
[view removeFromSuperview];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = @"Hello";
}
// Configure the cell.
return cell;
}
由於每一行的大小都不固定,因此您將無法重用它們,除非再次顯示相同的內容或某些相似的內容。
我的建議是為具有不同大小的每一行創建一個標識符。
您說過您有一個開關來基於indexPath添加內容,因此您應該根據其大小在每個case語句內使可重用單元格出隊。
嘗試為每個單元格指定一個唯一的標識符,
NSString * CellIdentifier = [NSString stringWithFormat:“ Cell%d”,indexpath.row];
不知道這是否是正確的方法,但是應該可以解決您的問題。
問題在於該單元格不是零,因此滾動時它多次返回同一單元格。 我從cellForRowAtIndexPath方法中刪除了條件。
if (cell == nil)
現在每次,它正在分配單元並正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.