Swift: Set UIButton background color to colorWithAlphaComponent for highlighted state
<p>I'm trying to set the background color of a custom <code>MyButton</code> UIButton to the button's current background color with an alpha component for a highlighted state. Similarly to how a UIButton's text title dims/darkens when the button is in a highlighted state.</p>

<p>I have been trying to achieve this for days, and ultimately came up with this line of code that seems to make the most sense, however, does not work:
<code>self.setBackgroundColor((self.backgroundColor?.colorWithAlphaComponent(0.5))!, forState: .Highlighted)
</code></p>

<p>I appreciate any help. Thank you!</p>

<pre><code>import UIKit

class MyButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.layer.cornerRadius = 25.0
        self.clipsToBounds = true
        self.setBackgroundColor((self.backgroundColor?.colorWithAlphaComponent(0.5))!, forState: .Highlighted)

    }

}

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
        CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, forState: forState)
    }
}
</code></pre>

<p><strong>UPDATE:</strong></p>

<p><a href="https://i.stack.imgur.com/0AyWY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0AyWY.png" alt="enter image description here"></a></p>