Lupo
Lupo

Reputation: 25

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

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.

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

What I tested so far:

Convert input data to Integer in Swift

Swift calculate value of UITextFields and return value

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 =)

Upvotes: 1

Views: 13399

Answers (2)

Orest Savchak
Orest Savchak

Reputation: 4569

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

//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

Upvotes: 1

Matt
Matt

Reputation: 1761

Connect your calculate button to below action.

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

Upvotes: 1

Related Questions