我有一个UIButton,当点击它时,背景图像会在OFF和ON图像之间变化。
我已经定义了这两个图像。
let offPosition = UIImage(named:"Dont Send.pdf")! as UIImage
let onPosition = UIImage(named:"send Button.pdf")! as UIImage
在我声明的视图控制器中,
var smsButtonActive = false
按钮有一个出口。
@IBOutlet weak var smsButton: PeControlButton!
我把按钮的Click定义为:
@IBAction func smsButtonClick(_ sender: PeControlButton){
if smsButtonActive {
smsButton.setBackgroundImage(onPosition, for: .normal)//on position
appSettings.set(smsButtonActive, forKey: "sendText")//writes status to appSettings
}else {
smsButton.setBackgroundImage(offPosition, for: .normal)//off position
appSettings.set(smsButtonActive, forKey: "sendText")//writes status to appSettings
}
smsButtonActive = !smsButtonActive
}
我的问题是,如果开关位置开始在On位置,它需要一次点击来改变图像。 如果它开始在关的位置,我必须双击才能让图像改变。 我知道这并不是什么大问题,因为图像会发生变化,但如果有人能给我指点一下,我就想弄清楚这个问题。
当你查看加载只是通过关闭的图像到你的按钮,这样的方式
var smsButtonActive = false. // false means our button image is on off mode
smsButton.setBackgroundImage(offPosition, for: .normal)//off position //
然后在你的按钮Action上,我们将改变下面的代码中的图像。
@IBAction func buttonClick(sender: any){
if smsButtonActive == false{ // when you first click on button then smsButtonActive is false then it goes to if condition where we are setting button on image because our but image by default in off mode and then we are also changing the smsButtonActive value change so when you click another time then smsButtonActive value(which is bool type) get True mode means it will goes to else part where we set the button off image.
smsButtonActive = true // here we are setting smsButton type so it will check the else part
smsButton.setBackgroundImage(onPosition, for: .normal)
appSettings.set(smsButtonActive, forKey: "sendText")
}else{
smsButtonActive = false
smsButton.setBackgroundImage(offPosition, for: .normal)//off position
appSettings.set(smsButtonActive, forKey: "sendText")//writes status to appSettings
}
也许这个对你有用,谢谢