2013-07-18 64 views
1

我在動態UITableView單元格中有一個標籤(quantitylbl)和一個步進器。我可以在更改步進值時更新UILabel,但是當滾動到該單元離開可見屏幕並再次滾動顯示標籤時,則步進值更改,標籤沒有更新。在日誌中,我可以看到更新後的值,但標籤未更新。幫助表示讚賞。這裏是代碼:滾動後,UILabel沒有在UITableViewCell中更新

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell; 
    UIStepper *stepper; 
    UILabel *quantitylbl; 

    int sectionCount = 0; 

    if ([indexPath section] == 1) sectionCount = 10; // Manage tags 

    switch ([indexPath row]) 
    { 
     case 2: 
      cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell2"]; 
      cell.textLabel.text = @"Quantity per day"; 
      cell.selectionStyle = UITableViewCellSelectionStyleNone; 

      stepper =[[UIStepper alloc] initWithFrame:CGRectMake(200, 60, 40, 20)]; 
      [stepper setStepValue:0.25]; 
      [stepper addTarget:self action:@selector(stepperPressed:) forControlEvents:UIControlEventValueChanged]; 
      stepper.tag = indexPath.section; 

      quantitylbl = [[UILabel alloc] initWithFrame:CGRectMake(160, 12, 40, 20)]; 

      if ([indexPath section] == 0) 
       quantitylbl.text = [self.milk1 objectForKey:@"Quantity"]; //get value from dict 
      else 
       quantitylbl.text = [self.milk2 objectForKey:@"Quantity"]; 

      [stepper setValue:[quantitylbl.text doubleValue]]; 
      quantitylbl.tag = sectionCount + [indexPath row]; 

      [cell setAccessoryView:stepper]; 
      [cell addSubview:quantitylbl]; 

      break; 

} 

- (IBAction)stepperPressed:(UIStepper *)sender 
{ 
    UILabel *label; 
    UITableViewCell* cell = [sender superview]; 
    NSString* strval = [NSString stringWithFormat:@"%.2f",sender.value]; 

    if (sender.tag == 0) 
    { 
     label = (UILabel *)[cell viewWithTag:2]; 
     [self.milk1 setValue:strval forKey:@"Quantity"]; 
     label.tag = 2; 
    } 
    else 
    { 
     label = (UILabel *)[cell viewWithTag:12]; 
     [self.milk2 setValue:strval forKey:@"Quantity"]; 
     label.tag = 12; 
    } 

    if (label != nil) 
    { 
     // I see correct value here, also label is updated correctly. But when I scroll the 
     // label out of screen and bring it back, the UILabel no more gets updated though 
     // I see correct values here.  
     label.text = strval; 
    } 
} 

回答

0

我認爲你使用錯誤的方法。您應該只從cellForRowAtIndexPath方法更新數據。更改stepperPressed方法中的類變量self.milk1,並在tableview中調用方法reloadData之後。

- (IBAction)stepperPressed:(UIStepper *)sender 
{ 
    NSString* strval = [NSString stringWithFormat:@"%.2f",sender.value]; 

    if (sender.tag == 0) 
    { 
     [self.milk1 setValue:strval forKey:@"Quantity"]; 
    } 
    else 
    { 
     [self.milk2 setValue:strval forKey:@"Quantity"]; 
    } 
    [self.tableView reloadData]; 
} 
+0

謝謝!這解決了我的問題,也更清潔的代碼:) – 09apps