swift - 如何使用我输入的 UITextField 值作为 swift 函数的参数值?

标签 swift

我需要能够获取我的 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/

相关文章:

regex - 在不使用 NSRegularExpression 的情况下,如何获取字符串正则表达式的所有匹配项?

ios - editButtonItem 不起作用

swift - 有更好的方法来使用这个 Switch func(Swift-Spritekit 项目)

swift - 在 swift 中为 UIBarButtonItem 设置背景图像

swift - 使用 PDF 来自 xcasset 的 "Error loading image resource'

swift - CBCentralManager 停止扫描需要多长时间?

ios - 如何从 iOS Swift Codable 中的 API 响应通知或打印模型类上缺少的键?

ios - 在函数调用中发送到实例的无法识别的选择器

ios - 如何一一删除MKAnnotation Pin?

swift - 端口扬声器的未知选定数据源(类型 : Speaker)?