我正在尝试创建一种禁用Button
的方法。这是我制作的应用程序,它是一个鸡蛋计时器,我遇到了一个bug;当我多次按下播放按钮时,定时器加速,我无法停止。我想创建一个禁用功能,但我在论坛上看到的所有内容都表示要使用。 enable = true
。当我使用这个Xcode时说它无效。在Xcode 8中启用和禁用按钮的正确代码是什么?
import UIKit
class ViewController: UIViewController {
var timer = Timer()
var myCount = 210
var button = 0
func processTimer() {
//what happens every second
counter()
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processTimer), userInfo: nil, repeats: true)
button = 1
}
func pauseTimer() {
timer.invalidate()
button = 0
}
func resetTimer(){
timer.invalidate()
myCount = 210
countdown.text = "\(myCount)"
button = 0
}
func counter() {
myCount -= 1
if myCount > 0 {
countdown.text = "\(myCount)"
} else {
countdown.text = "0"
timer.invalidate()
}
}
func add(){
myCount += 10
if myCount > 0 {
countdown.text = "\(myCount)"
} else {
countdown.text = "0"
}
}
func sub(){
myCount -= 10
if myCount > 0 {
countdown.text = "\(myCount)"
} else {
countdown.text = "0"
}
}
// timer countdown
@IBOutlet var countdown: UILabel!
// pause button
@IBAction func pauseButton(_ sender: AnyObject) {
pauseTimer()
print("Timer Paused")
}
//play button
@IBAction func playButton(_ sender: AnyObject) {
startTimer()
print("Timer started")
}
// -10 seconds
@IBAction func minusTen(_ sender: AnyObject) {
sub()
}
// reset timer to 290
@IBAction func resetButton(_ sender: AnyObject) {
resetTimer()
print("Timer Reset")
}
// +10 seconds
@IBAction func addTen(_ sender: AnyObject) {
add()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
countdown.text = "\(myCount)"
if button == 0{
playButton.enabled = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:2)
enabled/disable
Button
有两种方法。
playButton.isEnabled = false // This will give the (style) effect of disable to button
或
playButton.userInteractionEnabled = false // This will not give the (style) effect of disable
to button simply stop the user interaction
答案 1 :(得分:1)
您需要做的第一件事就是为按钮添加插座。您已经创建了该功能,但如果您想进行更改,则需要一个单独的插座 - 类似这样的
@IBOutlet weak var cmdPlayButton: UIButton!
然后,如果您想在计时器运行时防止多次按下按钮,则需要在按下按钮后立即禁用该按钮,并且仅在计时器结束时重新启用该按钮
//play button
@IBAction func playButton(_ sender: AnyObject) {
cmdPlayButton.enabled = false
startTimer()
print("Timer started")
}
只需记住在计时器完成或重置时启用按钮,您将需要处理暂停功能 - 您可以更改播放按钮上的文字以阅读“重启”按钮。例如。