【问题标题】:changing background Image of button being clicked更改背景图片被点击的按钮
【发布时间】:2020-09-09 23:38:10
【问题描述】:

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

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

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

      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
     }
    

    也许这对你有用。 谢谢

    【讨论】:

    • 嗨,Vipin,您的代码成功了,非常感谢。 (仍在尝试找出它为什么起作用)当我有一点时间时,我会再次深入了解它。
    • @stako 可能是您没有得到它,所以这就是为什么我只是放置一些 cmets 以便您理解。所以请再次阅读我的答案。谢谢
    猜你喜欢
    • 2013-07-13
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多