ios - 更改背景单击按钮的图像
问题描述
我有一个 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 位置开始,则需要单击一下来更改图像。如果它从关闭位置开始,我必须双击才能更改图像。我知道这不是一场大戏,因为图像发生了变化,但如果有人能指出我正确的方向,我想深入了解它。
解决方案
当您查看负载时,只需像这样将关闭图像传递给您的按钮
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
}
很可能这对你有用。谢谢
推荐阅读
- cordova - cordova-plugin-qrscanner 相机未显示
- node.js - Cloud Function for Firebase 部署时出错
- php - 捕获 Webhook 条目并放在新的 .csv 行上
- c++ - 确定夏令时是否适用于某个日期
- reactjs - 如何从函数返回单一类型
- python - For 循环 - 闰年输入
- c++ - 您如何修复阵列以使其正确?
- c# - 当我尝试从 URL 导入 XML 时,这无法正常工作
- python - 为什么我的 PyCharm 检查就像合法的 Python 3.8 代码是非法的一样?
- asp.net - 合并多个列表
在 LINQ 中分组时