首页 > 解决方案 > 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)

On the bottom left corner is the error i get after running on simulator. (On the picture there is M.Mansueli code)

标签: swiftxcode

解决方案


在类中创建按钮的@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)
}
}

推荐阅读