3

各行に float 値のラベルがある 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 に答える