2013-11-01 115 views
0

在我的故事板我有一個表視圖。 我使用從JSON文件(在viewDidLoad中加載)加載的數據填充該表視圖。UITableView重疊滾動

在我的UITableView中,我確實將「Prototype Cells」設置爲1,因此我可以輕鬆選擇一個附件。 我的原型單元有一個Seque到一個新的視圖,需要顯示所選項目的細節。

我填我的細胞編程方式使用這樣的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *videoTableIdentifier = @"VideoCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:videoTableIdentifier]; 

    if (cell == nil) 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:videoTableIdentifier]; 

    UILabel * title = [[UILabel alloc] initWithFrame:CGRectMake(40,5, 240,20)]; 
    [cell addSubview:title]; 
    [title setText:[[videos objectAtIndex:indexPath.row] objectForKey:@"title"]]; 

    UILabel * detail = [[UILabel alloc] initWithFrame:CGRectMake(40,28, 100,10)]; 
    [cell addSubview:detail]; 
    [detail setText:[NSString stringWithFormat:@"Year: %@", [[videos objectAtIndex:indexPath.row] objectForKey:@"year"]]]; 

    [cell addSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:[[videos objectAtIndex:indexPath.row] objectForKey:@"image"]]]]; 

    return cell; 
} 

當我開始滾動會發生以下情況: enter image description here

所以我開始尋找解決的辦法,我發現我必須設置: dequeueReusableCellWithIdentifier:videoTableIdentifier爲「無」。

雖然我這樣做,這解決了我的問題,但是現在我原型單元配件和Seque都不見了,所以我不能導航到下一個視圖了。

我找不到在互聯網上的解決方案,所以我決定問這個。 如果有人可以幫忙,會很棒。

回答

6

你的問題是,每次你重新使用一個單元格時,你都在爲它添加新的子視圖,所以如果你有一個單元格有一些標籤,並且你重複使用它並添加更多標籤,它們都會出現重疊。

我建議你製作自己的帶有標籤的自定義UITableViewCell,每次只更改標籤的值。

+0

這就是我的想法,因爲我已經閱讀了有關回收細胞的一些信息,但是我找不到如何解決這個問題。只有文本重疊,圖像保持不變,即使這也是子視圖?! – ronnyrr

+0

圖像堆疊在另一個上面。如果它有幫助,請接受答案 –

+0

實際上,您可以將if(cell == nil)條件中的addSubview代碼移入其中,並且無需創建UITableViewCell的子類就可以正常工作。但我認爲創建自定義子類仍然是一個更好的方法 – Lukas

0
if (!title){ 
    title = [[UILabel alloc] initWithFrame:CGRectMake(40,5, 240,20)]; 
    [cell addSubview:title]; 
} 
[title setText:[[videos objectAtIndex:indexPath.row] objectForKey:@"title"]]; 

以前的答案作者是對的。使用你自己的UITableViewCell的子類可能會更好。
我沒有看到任何內存版本。你在使用自動引用計數嗎?