我有一个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;
}
}
答案 0 :(得分: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]];
答案 1 :(得分:0)
你在哪里宣布了totalAmount?你有没有把它变成实例变量?这就是它保留其价值的原因。相反,您应该在本地声明totalAmount并将其初始化为零。
类似的东西:
else if(indexPath.section == 1)
{
double totalAmount = 0.0;
//.... Your code... And then Calculate totalAmount.
}
我认为它会以这种方式运作。