我创建了一堆文本字段和按钮。基本上,我想把账单金额和小费金额相乘,然后把总数除以人数。我在考虑让它们成为变量,但不知道该怎么做。

@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
}

最佳答案

基本上,您必须记住,IBOutlets引用的是UITextFields,而不是数字。
因此,考虑到这一点,您需要将字符串转换为双倍。这意味着您可以尝试从如下字符串中解析Double:

var text = String("5.0")
var double = Double(text)
print(double) // prints "5.0"

我还让它对您“安全”,因为如果文本不是double,则不会执行if语句,因此不会出现运行时错误,只是不会发生任何事情。这与UITextFields中没有“text”的工作方式相同,在UITextFields中,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)
        }

    }
}

10-08 07:30