在我的应用程序中,我有一个UIButton,可以同时启动和停止事件。我目前正在尝试使用以下IBAction以编程方式更改UIButton及其背景图片的标题:
@IBAction func StartandStop(sender: AnyObject) {
if StartandStop.titleLabel?.text == "Start Flight" {
StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
StartandStop.setImage(UIImage(named: "End"), forState: .Normal)
}
else if StartandStop.titleLabel?.text == "Stop Flight" {
StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
StartandStop.setImage(UIImage(named: "Start"), forState: .Normal)
}
}
我的程序是这样开始的:
然而,在我第一次按下按钮后:
当我继续按下按钮时,它仍处于第二状态。为什么我的按钮会这样做?
答案 0 :(得分:0)
使用func setBackgroundImage(_:, forState:)
代替func setImage(_:, forState:)
,此外,我会使用func titleForState(:)
代替titleLabel?.text
。
@IBAction func StartandStop(sender: AnyObject) {
let title = StartandStop.titleForState(UIControlState.Normal)
if title? == "Start Flight" {
StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
StartandStop.setBackgroundImage(UIImage(named: "End"), forState: .Normal)
}
else if title? == "Stop Flight" {
StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
StartandStop.setBackgroundImage(UIImage(named: "Start"), forState: .Normal)
}
}