添加 Double 和 String 以显示在 UILabel 上
Adding Double and a String to then display on a UILabel
我正在尝试将在文本字段中输入的值与指定为双精度的值相加,然后在标签上返回该值。我的代码是:
@IBOutlet weak var enterField: UITextField!
var weekOneTotal:Double = 0
@IBAction func addButton(_ sender: Any) {
addCorrectValue()
}
func addCorrectValue () {
guard let addAmount = convertAmount(input: enterField.text!) else {
print("Invalid amount")
return
}
let newValue = weekOneTotal += addAmount
secondScreen.weekOneAmountLabel.text = String(newValue)
}
func convertAmount (input:String) -> Double? {
let numberFormatter = NumberFormatter ()
numberFormatter.numberStyle = .decimal
return numberFormatter.number(from: input)?.doubleValue
}
您可能希望将 weekOneTotal
变量的值增加转换后的数量,然后您希望将此值用作某些标签的 text
weekOneTotal += addAmount
secondScreen.weekOneAmountLabel.text = String(weekOneTotal)
试试这个:
func addCorrectValue () {
guard let addAmount = Double(enterField.text!) else {
print("Invalid amount")
return
}
let newValue = weekOneTotal + addAmount
secondScreen.weekOneAmountLabel.text = "\(String(format: "%.1f", newValue))"
}
.1 是显示的小数位数。您可以根据需要进行调整。希望我理解了这个问题,这对你有用!
我正在尝试将在文本字段中输入的值与指定为双精度的值相加,然后在标签上返回该值。我的代码是:
@IBOutlet weak var enterField: UITextField!
var weekOneTotal:Double = 0
@IBAction func addButton(_ sender: Any) {
addCorrectValue()
}
func addCorrectValue () {
guard let addAmount = convertAmount(input: enterField.text!) else {
print("Invalid amount")
return
}
let newValue = weekOneTotal += addAmount
secondScreen.weekOneAmountLabel.text = String(newValue)
}
func convertAmount (input:String) -> Double? {
let numberFormatter = NumberFormatter ()
numberFormatter.numberStyle = .decimal
return numberFormatter.number(from: input)?.doubleValue
}
您可能希望将 weekOneTotal
变量的值增加转换后的数量,然后您希望将此值用作某些标签的 text
weekOneTotal += addAmount
secondScreen.weekOneAmountLabel.text = String(weekOneTotal)
试试这个:
func addCorrectValue () {
guard let addAmount = Double(enterField.text!) else {
print("Invalid amount")
return
}
let newValue = weekOneTotal + addAmount
secondScreen.weekOneAmountLabel.text = "\(String(format: "%.1f", newValue))"
}
.1 是显示的小数位数。您可以根据需要进行调整。希望我理解了这个问题,这对你有用!