-2

I need help with creating a button that allows me to multiply two numbers that I type into 2 separate text fields.

I have already created outlets for the button, text fields, and text holder where I want the answer to appear.

IBAction func OnButtonPress(_ sender: UIButton)

I just need to know what code to put under this outlet that would allow it to multiply the two numbers.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Adding another tag or two to the question might help get knowledgeable eyes on it, perhaps "interface-builder" ? (just a guess, based on https://stackoverflow.com/questions/1643007/iboutlet-and-ibaction#1643039 ) – jgreve Oct 25 '19 at 04:04
  • Start by breaking down your issues. You need to 1) Get the text from text fields; 2) Validate and convert the input to a number, maybe `Int` or `Double`; 3) Perform the calculation; 4) Convert the result back to a `String`; 5) Apply the `String` to some output. Start by researching each of those steps individual, but which time you should have all the information you need to solve your issue yourself – MadProgrammer Oct 25 '19 at 04:21
  • When reviewing the duplicate, ignore the currently accepted answer and look at the [second answer](https://stackoverflow.com/a/50099932/1226963). – rmaddy Oct 25 '19 at 04:37

1 Answers1

-1

Assuming these are your outlets:

@IBOutlet var num1: UITextField! // Input text field #1
@IBOutlet var num2: UITextField! // Input text field #2
@IBOutlet var product: UILabel!  // Text field with num1 x num2

To update the value of the product label, take the integer values of num1.text and num2.text and multiply:

@IBAction func OnButtonPress(_ sender: Any) {
   let n1: Int? = Int(num1.text)
   let n2: Int? = Int(num2.text)

   // Ensure that a number input exists for n1 and n2.
   if let safe1 = n1, safe2 = n2 {
      product.text = "\(safe1) x \(safe2) = \(safe1 * safe2)"
      // For example, if n1 = 3 and n2 = 4, then the output is "3 x 4 = 12".
   } else {
      product.text = "You didn't enter a number into both input fields!"
   }
}
Ben Myers
  • 1,173
  • 1
  • 8
  • 25