【发布时间】:2020-04-17 14:53:56
【问题描述】:
我正在尝试将 splitValue 和 tipPercent 的值放入底部的 getSettings() 中。为什么我可以在 IBAction calculatePressed 中获取这两个值的值,但是当我尝试将值获取到函数中时,值为零。我很困惑。感谢您的帮助!
@IBOutlet weak var billTextField: UITextField!
@IBOutlet weak var zeroPctButton: UIButton!
@IBOutlet weak var tenPctButton: UIButton!
@IBOutlet weak var twentyPctButton: UIButton!
@IBOutlet weak var splitNumberLabel: UILabel!
var tipChosen = ""
var totalPerPerson = ""
var tipPercent = ""
var splitValue = ""
@IBAction func tipChanged(_ sender: UIButton) {
tipPercent = sender.currentTitle!
if sender.isSelected == true {
return
}
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
if sender.currentTitle == "0%" {
tipChosen = "0.00"
} else if sender.currentTitle == "10%" {
tipChosen = "0.10"
} else if sender.currentTitle == "20%" {
tipChosen = "0.20"
}
billTextField.endEditing(true)
}
@IBAction func stepperValueChanged(_ sender: UIStepper) {
splitValue = String(Int(sender.value))
splitNumberLabel.text = String(Int(sender.value))
}
@IBAction func calculatePressed(_ sender: UIButton) {
let bill = Float(billTextField.text!)!
let tip = Float(tipChosen)!
let tax = bill * tip
let splitNumber = Float(splitNumberLabel.text!)
let total = (bill + tax) / Float(splitNumber!)
totalPerPerson = "$\(String(format: "%.2f", total))"
performSegue(withIdentifier: "goToTotal", sender: self)
}
func getSettings() -> String {
return "Split between \(splitValue) people, with a \(tipPercent) tip."
}
【问题讨论】:
-
您没有在 calculatePressed 中访问 splitValue 和 tipPercent,因此您的声明并不真正正确。此外,由于所有属性都初始化为“”,我真的不知道它们如何为零。如果您发布了导致问题的
getSettings的代码,将会有所帮助。另请注意,如果您正在使用您的属性进行计算,我建议您将它们转换为 int 或 double 之类的数字,而不是 text。 -
抱歉,您所说的“您的说法并不正确”是什么意思?我试过一次打印两个属性,它打印为零。
-
我的意思是你没有在函数
calculatePressed中访问它们中的任何一个,但你说你可以在那里获取值。这不是那么重要,重要的是它们为什么变成了 nil。您应该调试您的代码或在为它们赋值的地方使用打印语句。 -
哦,知道了。所有的信息都没有问题地通过,除了那个函数。我已经完成了所有的打印报表,他们都检查了。我尝试了很多方法将信息传递给该函数,但它们都返回 nil。
-
你从哪里调用它?
标签: swift function global ibaction