I'm new to Xcode and I'm using Swift to program a stopwatch. I have three functionalities - Play, Stop & Pause. Play and Pause should be the same button and alternate between states. How do I accomplish this in code?
我是Xcode的新手,我正在使用Swift来编写秒表。我有三个功能 - 播放,停止和暂停。播放和暂停应该是相同的按钮,并在状态之间交替。我如何在代码中完成此操作?
2 个解决方案
#1
You can user the property selected of button like this :
您可以像这样使用所选按钮的属性:
setup your button states in viewDidLoad
:
在viewDidLoad中设置按钮状态:
startButton.setTitle("Stop", forState: UIControlState.Selected)
startButton.setTitle("start", forState: UIControlState.Normal)
Now you can change the button states when it's tapped:
现在,您可以在点按时更改按钮状态:
@IBAction func startPauseAction(sender: UIButton) {
sender.selected = !sender.selected // action changed the selected
if sender.selected {
play()
} else {
pause()
}
}
#2
Using an enum for button state
使用枚举按钮状态
enum ButtonType {
case Stop
case Play
case Pause
}
var btnType: ButtonType = .Stop
@IBOutlet weak var actionBtn: UIButton!
@IBAction func buttonClicked(sender: UIButton) {
switch (self.btnType) {
case .Stop:
self.btnType = .Play
// TODO: Change button image/title for current state
break
case .Play:
self.btnType = .Pause
// TODO:
break
case .Pause:
// TODO:
break
}
}
#1
You can user the property selected of button like this :
您可以像这样使用所选按钮的属性:
setup your button states in viewDidLoad
:
在viewDidLoad中设置按钮状态:
startButton.setTitle("Stop", forState: UIControlState.Selected)
startButton.setTitle("start", forState: UIControlState.Normal)
Now you can change the button states when it's tapped:
现在,您可以在点按时更改按钮状态:
@IBAction func startPauseAction(sender: UIButton) {
sender.selected = !sender.selected // action changed the selected
if sender.selected {
play()
} else {
pause()
}
}
#2
Using an enum for button state
使用枚举按钮状态
enum ButtonType {
case Stop
case Play
case Pause
}
var btnType: ButtonType = .Stop
@IBOutlet weak var actionBtn: UIButton!
@IBAction func buttonClicked(sender: UIButton) {
switch (self.btnType) {
case .Stop:
self.btnType = .Play
// TODO: Change button image/title for current state
break
case .Play:
self.btnType = .Pause
// TODO:
break
case .Pause:
// TODO:
break
}
}