|
import UIKit |
|
|
|
class MyUIButton: UIButton { |
|
|
|
var highlightTitle = false |
|
var highlightBackground = false |
|
var highlightLayer = false |
|
|
|
override open var isHighlighted: Bool { |
|
didSet { |
|
guard let attributedString = attributedTitle(for: .normal) else { |
|
return |
|
} |
|
var attributes = attributedString.attributes(at: 0, effectiveRange: nil) |
|
let color = attributes[.foregroundColor] as? UIColor |
|
|
|
if isHighlighted { |
|
if highlightTitle { |
|
attributes[.foregroundColor] = color?.withAlphaComponent(0.5) |
|
} |
|
if highlightBackground { |
|
backgroundColor = backgroundColor?.withAlphaComponent(0.5) |
|
} |
|
if highlightLayer, |
|
let shapeLayer = layer.sublayers?[0] as? CAShapeLayer, |
|
let cgColor = shapeLayer.fillColor { |
|
let colorWithAlpha = UIColor(cgColor: cgColor).withAlphaComponent(0.5) |
|
shapeLayer.fillColor = colorWithAlpha.cgColor |
|
} |
|
} else { |
|
if highlightTitle { |
|
attributes[.foregroundColor] = color?.withAlphaComponent(1) |
|
} |
|
if highlightBackground { |
|
backgroundColor = backgroundColor?.withAlphaComponent(1) |
|
} |
|
if highlightLayer, |
|
let shapeLayer = layer.sublayers?[0] as? CAShapeLayer, |
|
let cgColor = shapeLayer.fillColor { |
|
let colorWithAlpha = UIColor(cgColor: cgColor).withAlphaComponent(1) |
|
shapeLayer.fillColor = colorWithAlpha.cgColor |
|
} |
|
} |
|
|
|
let newAttributedString = NSAttributedString(string: attributedString.string, |
|
attributes: attributes) |
|
setAttributedTitle(newAttributedString, for: .normal) |
|
} |
|
} |
|
|
|
convenience init(highlightTitle: Bool) { |
|
self.init(frame: .zero) |
|
self.highlightTitle = highlightTitle |
|
} |
|
|
|
convenience init(highlightBackground: Bool) { |
|
self.init(frame: .zero) |
|
self.highlightBackground = highlightBackground |
|
} |
|
|
|
convenience init(highlightLayer: Bool) { |
|
self.init(frame: .zero) |
|
self.highlightLayer = highlightLayer |
|
} |
|
|
|
} |
|
|
|
// Highlight atributed title |
|
let button1 = MyButton(highlightTitle: true) |
|
|
|
// Highlight view.background |
|
let button2 = MyButton(highlightBackground: true) |
|
|
|
// Highlight FIRST layer with roundedRect and shadow |
|
let button3 = MyButton(highlightLayer: true) |
|
let shadowLayer = CAShapeLayer() |
|
shadowLayer.path = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornerRadius).cgPath |
|
shadowLayer.fillColor = UIColor(red: 216, green: 66, blue: 152, alpha: 1).cgColor |
|
shadowLayer.shadowPath = shadowLayer.path |
|
shadowLayer.shadowColor = UIColor(red: 216, green: 66, blue: 152, alpha: 1).cgColor |
|
shadowLayer.shadowOffset = CGSize(width: 0, height: 5) |
|
shadowLayer.shadowOpacity = 0.5 |
|
shadowLayer.shadowRadius = 10 |
|
button3.layer.insertSublayer(shadowLayer, at: 0) // <---- IMPORTANT at 0 position |
|
|