I'll provide a Swift answer, which can be used without any customization, if you want the highlighted color to be a darkened version of the original background color. If you, on the other hand, want a completely different highlighted background color, you can supply that to the highlightedBackgroundColor property as a UIColor.
The following is the most efficient and straightforward way to implement such a functionality in Swift. It is also generic, meaning it can be used for lots of different buttons with different colors.
Here's the code:
import UIKit
class HighlightedColorButton: UIButton {
// A new highlightedBackgroundColor, which shows on tap
var highlightedBackgroundColor: UIColor?
// A temporary background color property, which stores the original color while the button is highlighted
var temporaryBackgroundColor: UIColor?
// Darken a color
func darkenColor(color: UIColor) -> UIColor {
var red = CGFloat(), green = CGFloat(), blue = CGFloat(), alpha = CGFloat()
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
red = max(red - 0.5, 0.0)
green = max(green - 0.5, 0.0)
blue = max(blue - 0.5, 0.0)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
// Set up a property observer for the highlighted property, so the color can be changed
@objc override var highlighted: Bool {
didSet {
if highlighted {
if temporaryBackgroundColor == nil {
if backgroundColor != nil {
if let highlightedColor = highlightedBackgroundColor {
temporaryBackgroundColor = backgroundColor
backgroundColor = highlightedColor
} else {
temporaryBackgroundColor = backgroundColor
backgroundColor = darkenColor(temporaryBackgroundColor!)
}
}
}
} else {
if let temporaryColor = temporaryBackgroundColor {
backgroundColor = temporaryColor
temporaryBackgroundColor = nil
}
}
}
}
}
Treat the button as a normal UIButton, with the addition of the optional property highlightedBackgroundColor:
let highlightedColorButton = HighlightedColorButton.buttonWithType(.Custom) as HighlightedColorButton
highlightedColorButton.backgroundColor = UIColor.redColor()
highlightedColorButton.highlightedBackgroundColor = UIColor.blueColor()