我需要能够获取我的 UITextField
值并将其用作 Double
来执行我函数中的计算;但是它没有返回正确的值。我想计算总金额并将其乘以百分比折扣。这是我的代码:
//Text Fields
@IBOutlet weak var amountTextField: UITextField!
@IBOutlet weak var percentDiscountTextField: UITextField!
func calculateAmount(percentage: Double) -> Double{
var percentage = (percentDiscountTextField.text as NSString).doubleValue
return (amountTextField.text as NSString).doubleValue - ((amountTextField.text as NSString).doubleValue * percentage)/100
}
@IBAction func calculatePressed(sender: AnyObject) {
var alert = UIAlertController(title: "Alert", message: "Please Enter a Value", preferredStyle: UIAlertControllerStyle.Alert)
if (count(amountTextField.text) == 0){
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else if (count(percentDiscountTextField.text) == 0){
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
var finalPrice: Double = calculateAmount()
}
}
最佳答案
我有点困惑为什么 calculateAmount
方法需要一个参数,但是当你调用它时你却没有提供一个参数?
我假设 calculateAmount
不应该接受任何参数,下面是我编写方法的方式:
func calculateAmount() -> Double? {
let percentageFromTextField = (percentDiscountTextField.text as NSString).doubleValue
let percentageOff = percentageFromTextField / 100.0
// Best to check the user entered a value in the correct range!
// Perhaps you could display a message saying the percentage discount
// wasn't in the correct range (if nil is returned)
if percentageOff < 0 || percentageOff > 1 { return nil }
let amount = (amountTextField.text as NSString).doubleValue
return amount * (1 - percentageOff)
}
希望对您有所帮助!
关于swift - 如何使用我输入的 UITextField 值作为 swift 函数的参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30000194/