2012-11-07 50 views
0

嗨,我一直在這個問題上連續呆了兩天,所以我問是否有任何人可以給我一隻手。我有一個tableview由4個部分組成。正確地爲單元格和子視圖分配標籤uitableview

部1 - >由只是1行,其中它的小區包含一個子視圖,其是一個UIImageView的

部2 - >由2個正常行(僅2樸素簡單細胞與它們的文本)

部3 - >由1個正常行的

部4 - >由1個行,其中它的小區包含一個子視圖,其是一個可以包含動態文本一個UITextView,所以UITextView的的高度並因此單元格高度取決於uitextview中文本的數量。

下面是創建這種結構的代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 


//create a nsstring object that we can use as the reuse identifier 
static NSString *CellIdentifier = @"Cell"; 

//check to see if we can reuse a cell from a row that has just rolled off the screen 
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

//if there re no cells that can be reused, create a new cell 
if(cell==nil){ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 


    switch (indexPath.section) { 
     case 0: 
      cell.selectionStyle = UITableViewCellSelectionStyleNone; 
      [cell.contentView addSubview:_viewForImageHeader]; 

      break; 

     case 1: 
      cell.selectionStyle = UITableViewCellSelectionStyleGray; 
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

      cell.textLabel.numberOfLines = 0; 
      cell.textLabel.lineBreakMode = 0; 
      cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:16.0]; 

      break; 

     case 2: 
      cell.selectionStyle = UITableViewCellSelectionStyleGray; 
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
      cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:16.0]; 
      break; 

     default: 
      cell.selectionStyle = UITableViewCellSelectionStyleNone; 
      [cell.contentView addSubview:_textViewForArticle]; 

      break; 

    } 

} 
else{ 

    NSLog(@"in else"); 

} 


//here i fill in the 2 normal cells with text 


return cell; 

} 

當UITableView的負載(在肖像模式)一切都很完美(圖像是在第1,第2和3包含其正確的文本,並在第4我有我的動態文本)。但是當我開始旋轉應用程序時,所有的單元格都混在一起了。例如,我在第4節找到第3節的內容,反之亦然。

我認爲這必須與事實,我不可能正確地重用細胞。我是否應該使用標籤,如果是,我如何在特定情況下實現標籤的使用?

回答

0

認沽switch情況外if條件 - 在if and else

+0

你是個天才!非常感謝! – puntotuning

+0

我試圖接受你的回答,但系統告訴我,我必須再等3分鐘。再次感謝! – puntotuning

0

之後是的,這是因爲重複使用的細胞。這裏有幾個選項,但是如果在這個tableView中永遠不會超過5個單元,那麼最簡單和最優化的解決方案就是不重用單元。換句話說,不是調用「dequeueReusableCellWithIdentifier」,而是每次分配一個新的單元格。

當你有更多的單元時,這會降低性能,但是如果你的單元是靜態的和有限的(因爲它們看起來像是),試圖重用單元沒有真正的收益。

如果你DID有4個「類型」的單元格和更多的行(動態分配的單元格更多),解決方法是爲每個單元格的4個「類型」分配UITableViewCell的子類,然後根據該部分或任何您的標準是。

+0

非常感謝你@HarryStack。所以按照你告訴我的,如果我使用user427969的解決方案,我每次都創建一個新單元,因此單元不會混淆。在我的項目中,我使用了user427969解決方案,但是我真的很感謝你的意見,我會牢記你告訴我以後的參考。 – puntotuning

+0

我很想upvote這個答案,以及user427969的一個,但我沒有15個代表點:( – puntotuning

相關問題