Skip to content

Instantly share code, notes, and snippets.

@npu3pak
Last active July 14, 2017 12:18
Show Gist options
  • Save npu3pak/65f2d3577db21f2b1c0e5484b5f20c08 to your computer and use it in GitHub Desktop.
Save npu3pak/65f2d3577db21f2b1c0e5484b5f20c08 to your computer and use it in GitHub Desktop.
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!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment