将两个文本字段的值相加等于标签总和的最简单方法是什么 [英] what's the easiest way to add the value of two text fields to equal a sum to a label

查看:64
本文介绍了将两个文本字段的值相加等于标签总和的最简单方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的方法是将两个 textField 的值相加,以等于标签的总和.
这是我正在使用的文本字段和标签:

what's the easiest way to add the value of two textField to equal a sum to a label.
Here are the text fields and label I am using:

@IBOutlet weak var f1TextField: UITextField!
@IBOutlet weak var f2TextField: UITextField!

@IBOutlet weak var speedLabel: UILabel!

我要在 f2TextField 中添加 f1TextField ,并在"speedLabel"中显示结果.

I want to add f1TextField with f2TextField and show the result in the "speedLabel".

推荐答案

您可以像下面这样使用功能迅速的功能:

You can use the power of functional swift like this:

if let textField1String = textField1.text, let textField2String = textField2.text {
    let arr = [textField1String, textField2String]
    let result = arr.compactMap({ Int($0) }).reduce(0, +) //Cast in Int value + using reduce to sum all the values of array
    speedLabel.text = "\(result)"
}

这篇关于将两个文本字段的值相加等于标签总和的最简单方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆