【问题标题】:How to connect multiple buttons in a storyboard to a single action in Swift 3 to increment value?如何将情节提要中的多个按钮连接到 Swift 3 中的单个操作以增加价值?
【发布时间】:2017-01-08 16:56:06
【问题描述】:

我希望用户按下四个按钮。按钮值为 1、5、25 和 100。

我设置了一个标签来显示按下的按钮的所有值的总和。

但是,由于 IBAction 按钮代码中的公式所在的位置,这些数字没有相加。我在之前的帖子中看到曾经有一个“连接动作”,它可以将情节提要中的多个 IBAction 按钮连接到使用 Swift 的单个动作。我在 Swift 3 中找不到该功能。

那么,如何将情节提要中的多个 IBActions 按钮连接到 Swift 3 中的单个操作?

下面的代码放在后面

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

var oneButtonTapped = 0
var noButtonTapped = 0
@IBAction func oneButtonTapped(_ sender: AnyObject) {oneButtonTapped = oneButtonTapped + 1

//Aware that the location of the code is requiring the 1 button to be tapped to be update.  TODO: Have the total update after every button tap

    let totalAmount = (noButtonTapped + oneButtonTapped + fiveButtonTapped + twentyfiveButtonTapped + hundredButtonTapped)

    Amount.text = String(totalAmount)
}
var fiveButtonTapped = 0
@IBAction func fiveButtonTapped(_ sender: AnyObject) {fiveButtonTapped = fiveButtonTapped + 5
}
var twentyfiveButtonTapped = 0
@IBAction func twentyfiveButtonTapped(_ sender: AnyObject) {twentyfiveButtonTapped = twentyfiveButtonTapped + 25
}
var hundredButtonTapped = 0
@IBAction func hundredButtonTapped(_ sender: AnyObject) {hundredButtonTapped = hundredButtonTapped + 100
}

提前感谢您的帮助,非常感谢!

【问题讨论】:

    标签: button action increment swift3


    【解决方案1】:

    这看起来与此线程 Connecting Multiple Buttons to a single IBAction 非常相似。基本上,您可以使用 Autolayout 的连接工具将多个按钮从故事板“控制拖动”到您的 swift 代码中先前创建的 IBAction。

    此链接Can multiple buttons be connected to a single IBAction 有一些显示连接过程的动画 GIF。

    然后您可以使用“sender”参数引用触发代码的按钮。

    顺便说一句,您的代码看起来好像位于 didReceiveMemoryWarning() 函数中。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-29
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      相关资源
      最近更新 更多