2011-10-08 41 views
1

我在嘗試實現複選框作爲待辦事項列表的一部分時遇到了一些麻煩。 我有一個UITableView,每個UITableViewCell都應該有自己的複選框,在左邊。如何在使用UITableViewCell緩存時將複選框添加到左側的UITableView?

如果有人能告訴我如何實現這一點,我將不勝感激。我已經廣泛地研究了這個網站上的問題,但仍然無法弄清楚如何實現這一點。

滾動tableview時會出現問題。例如,如果我有20個待辦事項,當我滾動時,將被選擇的複選框被取消選擇,並且將被取消選擇的複選框以看起來隨機的方式被選中。它必須是滾動的東西。

當系統重新使用單元時,究竟是什麼被緩存和發生?我是否抓住了一個空單元格,只是引用了裏面的空子視圖?

如果tablecell#1具有標籤爲10的視圖,tablecell#2是否能夠具有標籤爲10的視圖?或者是標籤不能在整個tableView中重複使用? (我甚至不確定這是否是問題)

謝謝!

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

switch (selectedSegment) { 

case Todos:{ 

      static NSString *ToDoCellIdentifier = @"TodoTableViewCell"; 
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifierToDoCellIdentifier]; 

      UITextView *taskTextView = nil; 
      UIButton *checkBox = nil; 
      UIImageView *highPriorityIcon = nil; 

      if (cell == nil) { 
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:signoutTableViewCellIdentifier] autorelease]; 


       checkBox = [[UIButton alloc]initWithFrame:CGRectMake(1, 1, 25, 25)]; 
       checkBox.tag = indexPath.row; 
       UIImage *normalImage = [UIImage imageNamed: @"[email protected]"]; 

       UIImage *selectedImage = [UIImage imageNamed: @"[email protected]"]; 
       [checkBox setImage:normalImage forState:UIControlStateNormal]; 
       [checkBox setImage:selectedImage forState:UIControlStateSelected]; 

       [checkBox addTarget:self action:@selector(historyButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
       [cell.contentView addSubview:checkBox]; 
       [checkBox release]; 

       //cell.contentView.backgroundColor = [UIColor lightGrayColor]; 
       cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
       NSLog(@"creating a new cell"); 

      } 

      if (!checkBox) { 

       checkBox = (UIButton*)[cell viewWithTag:indexPath.row]; 
      } 


      } 


      if ([[self.tasksCheckedStates objectAtIndex:indexPath.row]boolValue]) { 



       checkBox.selected = YES; 

      } 
      else { 


       checkBox.selected = NO; 
      } 



      return cell; 
      break; 
     } 

回答

1

你需要做到以下幾點:

  • 店在您的後臺數據模型選中/取消選中狀態,而不僅僅是你的細胞的屬性。單元格被重用,所以你不能使用單元格的屬性來實現持久性。
  • 在您的cellForRowAtIndexPath方法中,確保您取消選中您的指示器(但是您正在執行此操作)未檢查的項目,以及檢查檢查項目的指示器。再一次,這些單元格被重用,因此一個檢查過的單元格可能會被取消選中一個未檢查的項目。

編輯

你發佈你的代碼,我寫我的答案!我認爲你的問題是你分配給複選框的標籤。您不應該使用索引路徑行,因爲在您向下滾動到第20行時,您將無法引用此行。爲所有單元格複選框使用相同的標記,並且應該沒問題。您可以使用標籤區分超級視圖中的視圖,因此所有單元格中具有相同標籤的複選框都沒有問題。

關於另一個問題的另一點:當一個單元格從表中出列時,會返回原始對象,並返回前一次使用的所有視圖和數據。所以如果除了離開單元格之外你什麼也沒有做,只要缺失就創建它,然後返回它,你的第一個屏幕數據將繼續重複。操作中,你已經除了標籤問題之後,的正常過程是

  • 離隊細胞
  • 如果沒有返回小區,創建一個新的細胞,做基本的,不可更改配置
  • 設置特定行的單元格
相關問題