我创建了一堆文本字段和按钮。基本上,我想将账单金额乘以小费金额,并将总金额除以人数。我正在考虑制作变量,但不知道该怎么做。
@IBOutlet weak var billAmount: UITextField!
@IBOutlet weak var tipAmount: UITextField!
@IBOutlet weak var totalAmount: UITextField!
@IBOutlet weak var numberOfPeople: UITextField!
@IBOutlet weak var splitValue: UITextField!
@IBAction func splitBill(_ sender: UIButton) {
splitValue.text = totalAmount / numberOfPeople
}
@IBAction func totalAmount(_ sender: UIButton) {
let newBillAmount =
totalAmount.text = billAmount * tipAmount
}
答案 0 :(得分:1)
基本上你必须记住你的IBOutlets是引用UITextFields而不是数字。
因此,考虑到这一点,您需要从字符串转换为双打。这意味着您可以尝试从字符串中解析Double:
var text = String("5.0")
var double = Double(text)
print(double) // prints "5.0"
我也让你觉得“安全”,因为如果文本不是double,if语句就不会被执行,因此你不会得到运行时错误,只会发生什么。这对于UITextFields中没有“text”的方式也是一样的,其中if语句不会被执行,你只需让应用程序什么都不做。
结合所有这些东西给我们这样的东西:
class VC: UIViewController {
@IBOutlet weak var billAmount: UITextField!
@IBOutlet weak var tipAmount: UITextField!
@IBOutlet weak var totalAmount: UITextField!
@IBOutlet weak var numberOfPeople: UITextField!
@IBOutlet weak var splitValue: UITextField!
@IBAction func splitBill(_ sender: UIButton) {
if let totalAmountValue = Double(totalAmount.text!), let numberOfPeopleValue = Double(numberOfPeople.text!) { //safely get double values
splitValue.text = String(totalAmountValue / numberOfPeopleValue) //convert the quotient of the doubles into a string
}
}
@IBAction func totalAmount(_ sender: UIButton) {
if let billAmountValue = Double(billAmount.text!), let tipAmountValue = Double(tipAmount.text!) {
totalAmount.text = String(billAmountValue * tipAmountValue)
}
}
}