0

我希望将我拥有的两个值相加,然后将它们显示为新的 UILabel。

我已经在网上阅读了有关使用浮点数的信息,但是我遇到了困难,下面是我的代码..

我要做的总和是:shippingLabel(运费)+ costLabel(产品价格)然后在新的 UILabel 中访问它以显示(TotalPrice)

我遇到的问题是该值返回为 00.00

//TotalPrice
// Grab the values from the UITextFields.
float ShippingValue = [[shippingLabel text] floatValue];
float CostValue = [[costLabel text] floatValue];

// Sum them.
float floatNum = ShippingValue + CostValue;
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];

TotalPrice = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, 200.0f, 300.0f, 25.0f)];
TotalPrice.textColor = [UIColor colorWithHexString:@"5b5b5b"];
TotalPrice.backgroundColor = [UIColor clearColor];
TotalPrice.font = [UIFont boldSystemFontOfSize:12.0f];
TotalPrice.textAlignment = UITextAlignmentLeft;
[self.view addSubview:TotalPrice];
4

2 回答 2

1

考虑到您没有说明问题到底是什么,很难准确地回答这个问题。但是,最让我印象深刻的事情是:

TotalPrice1:您在创建之前分配了一个文本值。这些行应按以下顺序出现。

TotalPrice = [[UILabel alloc] initWithFrame:CGRectMake(60.0f, 200.0f, 300.0f, 25.0f)];
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];

2:您的评论表明您想将两个值相乘,但您使用了加法运算符。这可能不是你的问题,但我们都会犯愚蠢的错误。

// Multiply them.
float floatNum = ShippingValue * CostValue;

3:shippingLabel 文本的浮点值可能由于标签文本中的非数值而导致不准确。

旁注: 您应该这样命名变量,totalPrice而不是TotalPrice. 通常的做法是在实例上使用小写首字母,在类上使用大写字母。

于 2013-06-09T01:48:00.907 回答
0

我的猜测,你期望会有一个 UILabel 上面有一个总数,但事实是你根本看不到总数。我认为这是问题所在

TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];

您试图在 TotalPrice 尚未分配时将 TotalPrice 的文本设为总数,因此 TotalPrice 不会得到任何东西。您可以在分配 TotalPrice 后放置此行,它应该可以工作。愿它有所帮助。

于 2013-06-09T01:45:07.347 回答