swift - How to make button press change button background color and pressing again change it back on Xcode?
问题描述
Im creating my first app on Xcode and cant solve a problem to make a button change color on press and change back when pressed again.
I have found a code on previous topics here and I have created a button and created a function
@IBAction func Button1Pressed(_ sender: Any) {
if let button = sender as? UIButton {
if button.backgroundColor == UIColor.black {
button.backgroundColor = UIColor.red
}
else if button.backgroundColor == UIColor.red {
button.backgroundColor = UIColor.black
}
}
I run the code on simulator and i get an error on line
class AppDelegate: UIResponder, UIApplicationDelegate { = Thread 1: signal SIGABRT .
How can I make this code work correctly?
I tried M. Mansueli and Abishek solutions and both give me the same result with error: On the bottom left corner is the error i get after running on simulator. (On the picture there is M.Mansueli code)
解决方案
在类中创建按钮的@IBOutlet 引用,如图所示:
现在您可以使用以下方法更改印刷机颜色:
在您的 viewdDidLoad() 中添加此代码
override func viewDidLoad() {
button.setBackgroundImage(UIImage(color: .black), for: .normal)
button.setBackgroundImage(UIImage(color: .red), for: .highlighted)
}
添加 UIImage 扩展:
extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
推荐阅读
- php - 在新键上创建多个数组并检查相同的键,
- javascript - Laravel/Vuetify 需要一个合适的加载器来处理这种文件类型(mp4)
- reactjs - 如何在反应国际中添加格式化消息的链接?
- javascript - 跨包装的“catchError”处理程序的函数调用组合可观察对象
- c# - 使用什么 WPF 控件代替 ItemsControl 来创建一个画布,其中包含绑定到 ObservableCollection 的可自由放置的项目?
- python - 如何在使用鱼时停用 venv?
- kubernetes - 强制 Kubernetes 在所有 Pod 上分发请求
- php - 如何通过mysql查询查询数据作为zabbix系统信息小部件?
- c# - 如何从 csproj 项目文件中正确删除 NUnit3TestAdapter
- c# - 在实体框架中获取实体的所有列名