gpt4 book ai didi

ios - 如何在 Swift 中的 UILabel 上显示 Float 值?

转载 作者:可可西里 更新时间:2023-10-31 23:58:09 25 4
gpt4 key购买 nike

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var Screen: UILabel!
var firstNumber = Float()
var secondNumber = Float()
var result = Float()
var operation = ""
var isTypingNumber = false
@IBAction func Number(sender: AnyObject) {
isTypingNumber = false
var number = sender.currentTitle
if isTypingNumber == true {
Screen.text = Screen.text! + number!!;
} else {
Screen.text = number!!;
}
isTypingNumber = true
}
@IBAction func Operation(sender: AnyObject) {
operation = sender.currentTitle!!
isTypingNumber = false
firstNumber = Screen.text!.toInt()!
}
@IBAction func Equals(sender: AnyObject) {
secondNumber = Screen.text!.toInt()!
isTypingNumber = false
if operation == "+" {
result = firstNumber + secondNumber;
} else if operation == "-" {
result = firstNumber - secondNumber;
} else if operation == "x" {
result = firstNumber * secondNumber;
} else if operation == "/" {
result = firstNumber / secondNumber;
}
Screen.text = "\(result)"
}
@IBAction func Clear(sender: AnyObject) {
firstNumber = 0
secondNumber = 0
result = 0
Screen.text = "\(result)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

这是我的代码。我总是在 firstNumber = Screen.text!.toInt() 上收到错误“Int”无法转换为“Float”!和 secondNumber = Screen.text!.toInt()!
我正在尝试在 UILabel(Screen) 上显示一个 float 。我该怎么做?谁能告诉我如何在 UILabel 中使用 float 。这是 swift 。

谢谢,罗希特

最佳答案

您正在尝试将 Int 值分配给 Float 类型的变量。这在 swift 中是不允许的。你可以试试

let floatValue = (label.text as NSString).floatValue

要在 UILabel 中显示 floatValue,您可以在 swift 中使用字符串插值

label.text = "\(floatValue)"

要将 Int 转换为 Float,您可以这样做

floatValue = Float(intValue)

关于ios - 如何在 Swift 中的 UILabel 上显示 Float 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270320/

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