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.
}
}
这是我的代码。我总是得到错误'Int'在firstNumber = Screen.text!.toInt()上无法转换为'Float'!和secondNumber = Screen.text!.toInt()!
我试图在UILabel(屏幕)上显示一个浮动。我该怎么办?
有人能告诉我如何在UILabel中使用浮点数。这是斯威夫特。
谢谢, 罗希特夏尔
答案 0 :(得分:7)
您正在尝试将Int值分配给Float
类型的变量。这在swift中是不允许的。你可以尝试
let floatValue = (label.text as NSString).floatValue
并在floatValue
中显示UILabel
,您可以在swift中使用字符串插值。
label.text = "\(floatValue)"
要将Int
转换为Float
,您可以
floatValue = Float(intValue)
答案 1 :(得分:1)
问题是您将firstNumber
声明为Float,但是您要为该变量分配一个Int值。
变化:
firstNumber = Screen.text!.toInt()!
到
firstNumber = (Screen.text! as NSString).floatValue
注意:强>
类似也适用于secondNumber
。
答案 2 :(得分:1)
你可以试试这个:
@IBAction var label:UILabel!
var a:Float=1938.22
override func viewDidLoad(){
super.viewDidLoad()
label.text="\(a)"
}