|
import UIKit |
|
|
|
class TintedImageButton: UIButton { |
|
let normalColor = UIColor.turquoise |
|
let pressedColor = UIColor.lightSeaGreen |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
super.init(coder: aDecoder) |
|
setImage(self.imageView!.image?.tintedImage(normalColor), for: UIControlState()) |
|
setImage(self.imageView!.image?.tintedImage(pressedColor), for: .highlighted) |
|
setTitleColor(normalColor, for: UIControlState()) |
|
setTitleColor(pressedColor, for: .highlighted) |
|
} |
|
|
|
override func layoutSubviews() { |
|
super.layoutSubviews() |
|
let imageSize = imageView!.frame.size |
|
let titleSize = titleLabel!.frame.size |
|
|
|
let bufferMagnitude: CGFloat = 6 |
|
|
|
titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) |
|
|
|
if titleLabel?.text?.characters.count ?? 0 > 0 { |
|
imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + bufferMagnitude), 0, 0, -titleSize.width ) |
|
} |
|
|
|
titleEdgeInsets = UIEdgeInsetsMake((imageSize.height + bufferMagnitude), -imageSize.width, 0, 0); |
|
} |
|
} |
|
|
|
fileprivate extension UIImage { |
|
func tintedImage(_ color: UIColor) -> UIImage { |
|
let blendMode:CGBlendMode = .destinationIn |
|
UIGraphicsBeginImageContextWithOptions(self.size, false, 0) |
|
color.setFill() |
|
let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) |
|
UIRectFill(bounds) |
|
draw(in: bounds, blendMode: blendMode, alpha: 1) |
|
let tintedImage = UIGraphicsGetImageFromCurrentImageContext() |
|
UIGraphicsEndImageContext() |
|
return tintedImage! |
|
} |
|
} |