0

I am creating a button that when clicked it will change its own color. The problem is its background color is gradient so i have to addSublayer. But I want to change to another color, when running the machine will crash.

    @IBAction func actionMute(_ sender:AnyObject!) {

        hasMuted = !hasMuted
        
        let colorTop =  UIColor(red: 17/255.0, green: 168/255.0, blue: 153/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 1/255.0, green: 107/255.0, blue: 184/255.0, alpha: 1.0).cgColor
        let gradientLayer1 = CAGradientLayer()
        gradientLayer1.colors = [colorTop, colorBottom]
        gradientLayer1.locations = [0.0, 1.0]
        gradientLayer1.frame = self.muteBtn.bounds
        gradientLayer1.cornerRadius = 40
        
        let gradientLayer2 = CAGradientLayer()
        gradientLayer2.colors = [UIColor.red.cgColor, UIColor.white.cgColor]
        gradientLayer2.locations = [0.0, 1.0]
        gradientLayer2.frame = self.muteBtn.bounds
        gradientLayer2.cornerRadius = 40
        
        if hasMuted {
            self.muteBtn.layer.borderColor = UIColor(red:248/255, green:249/255, blue:252/255, alpha: 1).cgColor
            self.muteBtn.layer.backgroundColor = UIColor.white.cgColor
            self.muteBtn.layer.sublayers[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer2, at: 0)
        } else {
            self.muteBtn.layer.borderColor = UIColor(red:17/255, green:168/255, blue:253/255, alpha: 1).cgColor

            //background
            self.muteBtn.layer.backgroundColor = colorBottom
            self.muteBtn.layer.sublayers?[0].removeFromSuperlayer()
            self.muteBtn.layer.insertSublayer(gradientLayer1, at: 0)    
        }
    }

The error when app crash like this:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0xee9b537b0)
    frame #0: 0x00000001988fecf4 libobjc.A.dylib`objc_msgSend + 20
libobjc.A.dylib`objc_msgSend:
->  0x1988fecf4 <+20>: ldr    x11, [x16, #0x10]
    0x1988fecf8 <+24>: and    x10, x11, #0xfffffffffffe
    0x1988fecfc <+28>: tbnz   w11, #0x0, 0x1988fed50    ; <+112>
    0x1988fed00 <+32>: eor    x12, x1, x1, lsr #7
Target 0: (Runner) stopped.
[log] methodCallHandler onCallToggleMic
Lost connection to device.
Exited

The button like this

After removing the line removeFromSuperlayer(), the app runs normally but not only changes color once. Is there a way to create a button similar to this?

thienphan
  • 9
  • 2

0 Answers0