I provided a Swift answer that you can use without any configuration 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 provide this highlightBackgroundColor property as UIColor.
Below is the most efficient and easiest way to implement such a function in Swift. It is also general, that is, it can be used for many different buttons with different colors.
Here is 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 regular UIButton by adding the additional highlightBackgroundColor property:
let highlightedColorButton = HighlightedColorButton.buttonWithType(.Custom) as HighlightedColorButton highlightedColorButton.backgroundColor = UIColor.redColor() highlightedColorButton.highlightedBackgroundColor = UIColor.blueColor()
ArVID220u Nov 22 '14 at 22:53 2014-11-22 22:53
source share