[英]Adding values in iOS using float
我正在尋找求和的兩個值,然后將它們顯示為新的UILabel。
我已經在線閱讀了有關使用float的信息,但是我仍未解決,這是下面的代碼。
我想做的總和是: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];
考慮到您尚未說明問題的確切原因,很難准確地回答這個問題。 但是,最讓我驚訝的事情是:
1:創建文本之前,您要TotalPrice
分配文本值。 這些行應按以下順序顯示。
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
。 通常的做法是在實例上使用小寫的首字母,在類上使用大寫。
我的猜測是,您期望會有一個帶有總數的UILabel,但事實是您根本看不到總數。 我認為這是問題所在
TotalPrice.text = [[NSString alloc] initWithFormat:@"%f", floatNum];
您試圖使TotalPrice的文本成為總數,而尚未分配TotalPrice,因此TotalPrice不會得到任何東西。 您可以在分配TotalPrice之后將其放在行中,它應該可以工作。 希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.