3

我有一个 UITableView,每行都有一个带有浮点值的标签。最后一行中的最后一个标签应显示总金额。

它显示的总金额很好,但如果 tableView 滚动到屏幕外并返回,金额会增加。

 if(tableView == self.allTab)
{
if(indexPath.section == 0)
    {
        self.firstLabel.text = @"Category";
        self.firstLabel.textColor = [UIColor redColor];
        self.secondLabel.text = @"Date";
        self.secondLabel.textColor = [UIColor redColor];
        self.thirdLabel.text = @"Amount";
        self.thirdLabel.textColor = [UIColor redColor];
    }  

else if(indexPath.section == 1)
    {
        NSManagedObject *records = nil;
        records = [self.listOfExpenses objectAtIndex:indexPath.row];
        self.firstLabel.text = [records valueForKey:@"category"];
        NSString *dateString = [NSString stringWithFormat:@"%@",[records valueForKey:@"date"]];
        NSString *dateWithInitialFormat = dateString;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
        NSDate *date = [dateFormatter dateFromString:dateWithInitialFormat];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
        NSString *dateWithNewFormat = [dateFormatter stringFromDate:date];
        self.secondLabel.text = dateWithNewFormat;
        NSString *amountString = [NSString stringWithFormat:@"%@",[records valueForKey:@"amount"]];
        self.thirdLabel.text = amountString;
        totalAmount = totalAmount + [amountString doubleValue];
    }

else if(indexPath.section == 2)
{
        self.firstLabel.text = @"Total";
        self.firstLabel.textColor = [UIColor redColor];
        self.thirdLabel.text = [NSString stringWithFormat:@"%.2f",totalAmount];
        self.thirdLabel.textColor = [UIColor redColor];
        self.thirdLabel.adjustsFontSizeToFitWidth = YES;
}
}
4

2 回答 2

1

您不应该在 cellForRowAtIndexPath 内计算总计,因为当它再次滚动它时会计算总计,因此请使用其他方法计算总计,如下所示:

-(float)calculateTotal
{
    totalAmount = 0;
   for(int i =0;i<[self.listOfExpenses length];i++)
   {
      NSManagedObject *records = nil;
        records = [self.listOfExpenses objectAtIndex:i];
      NSString *amountString = [NSString stringWithFormat:@"%@",[records valueForKey:@"amount"]];
      totalAmount = totalAmount + [amountString doubleValue];
   }

 return totalAmount;
} 

并将其分配如下:

 self.thirdLabel.text = [NSString stringWithFormat:@"%.2f",[self calculateTotal]];
于 2012-07-04T11:30:53.690 回答
0

你在哪里申报了totalAmount?您是否将其设为实例变量?这就是它保持其价值的原因。相反,您应该在本地声明 totalAmount 并将其初始化为零。

就像是:

else if(indexPath.section == 1)
{
    double totalAmount = 0.0;
    //.... Your code... And then Calculate totalAmount.
}

我认为它会以这种方式工作。

于 2012-07-04T11:30:11.933 回答