【问题标题】:I can't figure out UIButton with Three States (Start, Stop, and reset)我无法弄清楚具有三种状态(启动、停止和重置)的 UIButton
【发布时间】:2020-03-09 18:12:07
【问题描述】:

我正在自学如何编写 Swift 代码,我知道它并不漂亮,但我希望更多地让它首先工作。我知道我需要什么,但我无法弄清楚。我有一个带有一个动作的按钮,当你点击它时,我需要它来改变颜色、标题和功能。我改变了颜色和标题,但改变功能很难。似乎我需要将一个新函数传递给计时器内的“startTapped”函数,但我想不出一个好方法。它可能与 loadView() 的生命周期有关

timerView.actionButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)

这里是完整的代码 sn-p:

        view = timerView
        timerView.installContraints()
        timerView.actionButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
    }

    @objc func startTapped() {
        print("button pressed")
        activeTimer?.invalidate()

        let startDate = Date()
        activeTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in
            let currentDate = Date()
            let duration = currentDate.timeIntervalSince(startDate)

            func formatDuration(DoubleDuration: (Double) -> String) {
                // make number formatter function to format the TimeInterval Double into a String??
            }

            self.timerView.timerLabel.text = "\(duration)"
        })
        timerView.actionButton.setTitle("STOP", for: .normal)
        timerView.actionButton.setTitleColor(.white, for: .normal)
        timerView.actionButton.backgroundColor = .red
    }

    func stopTapped() {
        print("stop tapped")
        activeTimer?.invalidate()
    }

    func resetTapped() {
        print("something")
    } ```



【问题讨论】:

标签: swift uibutton


【解决方案1】:

如果您想始终按照启动/停止/重置的顺序执行操作,请添加索引变量

var index = 0

然后添加一个新函数,该函数根据index 调用其他函数,然后递增索引

@objc func buttonTapped(_ sender : UIButton) {
     if index == 0 {
        startTapped()
     } else if index == 1 {
        stopTapped()
     } else {
        resetTapped()
     }
     index = (index + 1) % 3
}

并将此功能用作按钮操作

timerView.actionButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

【讨论】:

  • 非常感谢,就是这样!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 2014-04-03
相关资源
最近更新 更多