我正在开发一个简单的计算器应用程序。我有用于输入的“文本框”和用于输出的标签,两者都放置在 View Controller 中。
我想将文本框中的输入作为整数,进行一些数学计算,例如乘法,然后输出到文本标签。
如何进行这样的简单计算?
使用此代码,我在 var mDeposit = EnterMoneyAmount - Deposit
行上收到错误:
Binary operator '-' cannot be applied to operands of type 'UITextField' and 'Int'
import UIKit
class ViewController: UIViewController {
let fee = 1.20
let tax = 1.07
let deposit = 100
@IBOutlet weak var moneyResults: UILabel!
@IBOutlet weak var enterMoneyAmount: UITextField!
@IBAction func buttonPressed(_ sender: AnyObject) {
var mDeposit = enterMoneyAmount - deposit // Error here
var mDepositAndFee = mDeposit * fee
var mDepositAndFeeAndTax = mDepositAndFee * tax
mDepositAndFeeAndTax.text = moneyResults
}
}
最佳答案
您需要将 UItextLabel 的文本设置为等于按下按钮后计算得到的值。
@IBAction func buttonPressed(_ sender: AnyObject) {
endingCash = ((startingCash * fee) + (endingCash * tax) + (endingCash + deposit))
moneyResults.text = endingCash
}
关于ios - 从 UITextField 获取一个值,计算另一个值,然后更新 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096502/