gpt4 book ai didi

iphone - uitableview 的最后一行中的值发生变化

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:25:05 25 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

您不应该在 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]];

关于iphone - uitableview 的最后一行中的值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11328040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com