首页 > 解决方案 > 更改背景单击按钮的图像

问题描述

我有一个 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!

我已将按钮单击定义为:

@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 位置开始,则需要单击一下来更改图像。如果它从关闭位置开始,我必须双击才能更改图像。我知道这不是一场大戏,因为图像发生了变化,但如果有人能指出我正确的方向,我想深入了解它。

标签: iosswiftuibutton

解决方案


当您查看负载时,只需像这样将关闭图像传递给您的按钮

  var smsButtonActive = false. // false means our button image is on off mode 
  smsButton.setBackgroundImage(offPosition, for: .normal)//off position // 

之后在您的按钮操作上,我们将更改以下代码中的图像

@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
 }

很可能这对你有用。谢谢


推荐阅读