【问题标题】:How to append array with UITextField input?如何使用 UITextField 输入附加数组?
【发布时间】:2019-09-30 12:16:27
【问题描述】:

我有一个任务是制作一个计算器来计算给定输入的平均数量。 我需要接受并显示在range 中输入的介于 0 和 100 之间的数字(“添加”按钮)。并计算并显示平均值。

有一个UITextField,我在其中输入数字,然后按添加按钮将其显示为label/textview(我不确定要使用哪个)。

应将数字附加到数组中,以便使用averageOf() 函数。

我已尝试显示数字,但 label 替换了新数字而不是添加它。我对 swift 很陌生,不知道如何编写代码以仅接受一定范围的数字。

我的文本字段:

@IBOutlet weak var txtInput: UITextField!

添加按钮:

@IBAction func btnAdd(_ sender: UIButton) {
        let testScore = txtInput.text
        scoreDisplay.text = testScore
    }

数字的输出/显示应该是,例如,40, 23.6, 98.2, 74.4 我得到的只是数字的替换。

【问题讨论】:

    标签: arrays swift button uitextfield label


    【解决方案1】:

    您应该使用+= 而不是= 追加(替换整个值)

    scoreDisplay.text += ", \(testScore)"
    scoreDisplay.text = scoreDisplay.trimmingCharacters(in: CharacterSet(charactersIn: " ,"))
    

    修剪用于删除字符串中的第一个,

    编辑

    由于UILabeltext 属性是Optional<String>,因此您实际上不能使用+=。所以:

    scoreDisplay.text = scoreDisplay.text ?? "" + ", \(testScore)"
    scoreDisplay.text = scoreDisplay.text?.trimmingCharacters(in: CharacterSet(charactersIn: " ,"))
    

    【讨论】:

    • 我做了一个错误“表达式类型'@lvalue String?'在没有更多上下文的情况下是模棱两可的”。不确定这意味着什么以及如何解决?
    • @KHY 这是因为text 属性是可选的,请检查我的编辑
    【解决方案2】:

    编辑:我发现了问题。 scoreDisplay.text 和 testScore.text 都是可选的,因此您必须确保它们具有值。

    @IBAction func btnAdd(_ sender: UIButton) {
       guard let testScore = txtInput.text, let scoreDisplay = scoreDisplay.text else  { return }
       scoreDisplay.text = scoreDisplay + testScore
      } 
    

    另外,如果你想在每个数字中间加上“,”:

    @IBAction func btnAdd(_ sender: UIButton) {
       guard let testScore = txtInput.text, let scoreDisplay = scoreDisplay.text else  { return }
       scoreDisplay.text = "\(scoreDisplay), \(testScore)"
      }
    

    PD:= 仅将您的字符串替换为其他字符串,+= 附加一个新字符串。

    【讨论】:

    • 它给出了一个错误“表达式类型'@lvalue String?'在没有更多上下文的情况下模棱两可“你知道如何将 tex 字段中的输入数字同时添加到数组中吗?
    • 你的数组是什么类型的数据? [字符串] , [整数], [双] ... ?
    • 数据类型为Double
    • 在你想将输入添加到数组的函数中试试这个:if let testScore = Double(txtInput.text) { theNameOfYourArray.append(testScore) }
    • 您询问 txtInput.text 是否可以转换为双精度数,如果可能,追加到您的数组中。
    猜你喜欢
    • 2020-12-01
    • 2017-12-24
    • 2019-11-23
    • 2017-12-25
    • 2015-10-12
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多