选择基于文本字段留空的计算

时间:2018-01-07 01:59:10

标签: ios swift uitextfield

我正在尝试创建一个使用3个变量的代码(在Swift 4 xcode 9中),其中2个由用户通过textfields给出。将根据哪个变量留空来计算另一个变量的值。例如,如果用户将textfield1留空,则当按下按钮时,textfield2和textfield3的输入将用于计算。如果用户将textfield2留空,则使用textfield1和textfield3的输入等等......我还设置了委托,将UITextField转换为float等等。

我正在尝试创建一个基于哪个文本字段留空的选择器,但没有成功......

提前致谢!

//instance variables to hold values entered by the user
var one : Float = 0
var two : Float = 0
var three : Float = 0

//TextFields variables
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
@IBOutlet weak var textField3: UITextField!

func calculate() {
    var result : Float = 0

    // *** Selector ***

    //if user leaves textfield1 blank
    if (textField1.text?.isEqual(nil))! {
        result = textField2 * textfield3
        resultLabel.text = "\(result)"
        }

    //if user leaves textField2 blank
    else if (textField2.text?.isEqual(nil))! {
        result = textfield1 / textField3
        resultLabel.text = "\(result)"
            }

    //if user leaves textField3 blank
    else if (textfield3.text?.isEqual(nil))! {

        result = textfield1 + textfield2
        resultLabel.text = "\(result)"
            }
    }

2 个答案:

答案 0 :(得分:0)

您正试图在UITextField上执行数学运算,这显然是不可能的。文本字段包含字符串。你想对这些字符串所代表的Float进行数学运算。

如果你稍微概括一下你的问题,它基本上归结为:

  • 找出三个字段中哪一个是空的(只允许1个字段)
  • 将其他2个字段的字符串值转换为Float s
  • 对这2个Float执行数学运算并将结果输出到标签

代码:

func calculate() {
    // These are the possible operations that you will perform
    // Each is a closure that takes 2 Floats and return a Float
    let plus     = { (lhs: Float, rhs: Float) in lhs + rhs }
    let multiply = { (lhs: Float, rhs: Float) in lhs * rhs }
    let divide   = { (lhs: Float, rhs: Float) in lhs / rhs }

    var lhsStr = ""         // the string stored in the first non-empty text field
    var rhsStr = ""         // the string stored in the second non-empty text field
    var operation = plus    // don't worry about the default. We will change this later

    // Find which field is empty
    // We allow only one of the fields to be empty, not 0, 2, or 3.
    switch (textField1.text!.isEmpty, textField2.text!.isEmpty, textField3.text!.isEmpty) {
    case (true, false, false):
        lhsStr = textField2.text!
        rhsStr = textField3.text!
        operation = multiply
    case (false, true, false):
        lhsStr = textField1.text!
        rhsStr = textField3.text!
        operation = divide
    case (false, false, true):
        lhsStr = textField1.text!
        rhsStr = textField2.text!
        operation = plus
    default:
        fatalError("One and only one of the fields must be empty")
    }

    // Now convert the 2 Strings to Floats
    if let lhs = Float(lhsStr), let rhs = Float(rhsStr) {
        let result = operation(lhs, rhs)
        resultLabel.text = "\(result)"
    } else {
        fatalError("Cannot convert string to number")
    }
}

答案 1 :(得分:0)

您要做的是非常手动,而不是推荐的方式。 Swift支持很多转换函数来完成这些工作。

首先创建一个数组来存储文本字段:

var inputs: [UITextField] = [UITextField]()

override func viewDidLoad() {
    super.viewDidLoad()

    inputs.append(textField1)
    inputs.append(textField2)
    inputs.append(textField3)
}

现在您拥有所有输入的数组。我们现在的工作是转换输入并获得结果值:

func calculation() {
    var blankIndex = 0 // keep track of which input is blank

    // let transform our inputs into float values
    let values = inputs.enumerated()
        .map { (i, textField) -> Float? in
            if let text = textField.text, !text.isEmpty {
                blankIndex = i // we know which input is blank
                return Float(text)!
            }
            return nil
        }
        .filter { $0 != nil }
        .map { $0! }

    // now we need to validate out inputs
    // only one input is left blank by the user
    if values.count != 2 {
        // show alert for notifying user about this

        // stop our calculation
        return
    }

    // now our values contain only valid inputs the we need,
    // we can start do our calculation now
    let result: Float
    switch blankIndex {
    case 0: result = values[0] * values[1]
    case 1: result = values[0] / values[1]
    default: result = values[0] + values[1]
    }
}

此时,结果变量是您需要的结果