我如何创建允许我将两个数字相乘的代码? [重复]

问题描述 投票:-2回答:1

我在创建按钮时需要帮助,该按钮使我可以将输入的两个数字相乘成2个单独的文本字段。

我已经为我希望答案出现的按钮,文本字段和文本持有人创建了出口。

IBAction func OnButtonPress(_ sender: UIButton)

我只需要知道在此出口下放置什么代码,即可使两个数字相乘。

swift operators interface-builder
1个回答
-1
投票

假设这些是您的店铺:

@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

要更新product标签的值,请取num1.textnum2.text的整数并乘以:

@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!"
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.