【问题标题】:Selecting calculation based o which textfield is left blank根据留空的文本字段选择计算
【发布时间】:2018-01-07 01:59:10
【问题描述】:

我正在尝试制作一个使用 3 个变量的代码(在 Swift 4 xcode 9 中),其中 2 个由用户通过文本字段给出。另一个变量的值将根据哪个变量留空来计算。例如,如果用户将 textfield1 留空,那么当按下按钮时,来自 textfield2 和 textfield3 的输入将用于计算。如果用户将 textfield2 留空,则使用 textfield1 和 textfield3 的输入等等...我还设置了代表,将 UITextField 转换为浮点数等。

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

提前致谢!

//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)"
            }
    }

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    您正在尝试做的是手动操作,而不是推荐的方式。 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]
        }
    }
    

    此时result变量就是你需要的结果

    【讨论】:

    • 数组“inputs”总是有三个元素(变量),但数组“values”只显示两个元素,所以当代码执行计算时会出现“越界”崩溃。对于验证,我在输入中使用 var isValid = true 作为 textField { if textField.isEqual("") { isValid = false } else { isValid = true } }
    • 我的代码假定您的要求(只有一个输入留空)得到验证。因此,它可能会导致索引超出范围异常。请更新我的答案
    【解决方案2】:

    您正在尝试对UITextFields 执行数学运算,这显然是不可能的。文本字段包含字符串。您想对这些字符串表示的 Floats 进行数学运算。

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

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

    代码:

    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.为什么sender 声明为NSObject?这是斯威夫特。将其声明为特定的对象类型(UIButton 等)或至少 Any。 2. 为什么是Float 而不是Double? 3.UITextField text 不会返回nil。强制展开总是安全的。 let isField1Empty = textField1.text!.isEmpty
    • 1.那是一个错字。 2. OP 使用了Float,所以我只是假设。 3. UIKit 不会将nil 分配给UITextField.text 但是用户代码呢?该属性是可选的,因此将nil 分配给它是完全有效的。
    • iOS 10或更高版本可以使用UIKeyInput属性hasTextdeveloper.apple.com/documentation/uikit/uikeyinput/…
    • 3.如果您将nil 分配给文本字段的text 属性,然后立即将其读回,您会得到一个空字符串,而不是nil。正如我所说,强制解开UITextField 的text 属性总是安全的。它已记录在案。试试看。
    • btw textField1.text?.isEmpty ?? true 是错误的,它应该是 textField1.text?.isEmpty == true 或者只是 textField1.text!.isEmpty 考虑到 text 属性永远不会返回 nil 它的默认值是一个空字符串
    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多