在 Xcode 8 和 Swift 3 中将 UITextField 转换为 Integer 并用它们计算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41395256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:41:40  来源:igfitidea点击:

Convert UITextField to Integer in Xcode 8 and Swift 3 and calculate with them

iosiphonexcodeswift3

提问by Lupo

I searched the whole internet but only found solutions for Swift 2 or outdated Xcode versions which doesnt help me :/ Also Im very new to Xcode and Swift, so please excuse that.

我搜索了整个互联网,但只找到了 Swift 2 或过时的 Xcode 版本的解决方案,这对我没有帮助:/我对 Xcode 和 Swift 也很陌生,所以请原谅。

I want the user to input some numbers in several UITextFields and then press a "calculate" button which shows the result in a UILabel.

我希望用户在几个 UITextField 中输入一些数字,然后按下一个“计算”按钮,在 UILabel 中显示结果。

What I tested so far:

到目前为止我测试的内容:

Convert input data to Integer in Swift

在 Swift 中将输入数据转换为整数

Swift calculate value of UITextFields and return value

Swift 计算 UITextFields 的值并返回值

So my code looks really poor so far. Nothing worked so thats all I have and the comment shows how I want it to be:

所以到目前为止我的代码看起来很糟糕。没有任何效果,所以这就是我所拥有的,评论显示了我想要的样子:

import UIKit

class ViewController: UIViewController {

    //elements from the viewcontroller
    @IBOutlet weak var input1: UITextField!
    @IBOutlet weak var input2: UITextField!
    @IBOutlet weak var calculate: UIButton!
    @IBOutlet weak var output: UILabel!

    //calculation
    //Just simple math like
    //output = input1 + input2
    //or output = (input1 + 50) + input2






    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Thank you for helping me out =)

谢谢你帮助我=)

采纳答案by Orest Savchak

First of all, you need to create an IBAction for your button by dragging from Storyboard. I think it is not a problem.

首先,您需要通过从 Storyboard 中拖动来为您的按钮创建一个 IBAction。我认为这不是问题。

//imagine this is your IBAction function on calculate click
@IBAction func calculate(_ sender: UIView) {
  output.text = String(Int(input1.text!)! + Int(input2.text!)!)
}

I skipped all validations, but for the happy path it should work

我跳过了所有验证,但对于快乐路径它应该可以工作

回答by Matt

Connect your calculate button to below action.

将您的计算按钮连接到以下操作。

@IBAction func calculate(sender: Any) {
    let result = Int(input1.text!) + Int(input2.text!)
    output.text = "\(result)"
}