Skip to content

Instantly share code, notes, and snippets.

@npu3pak
Created February 18, 2017 18:09
Show Gist options
  • Save npu3pak/4dc3eab77507d15fde6760d7a919f94d to your computer and use it in GitHub Desktop.
Save npu3pak/4dc3eab77507d15fde6760d7a919f94d to your computer and use it in GitHub Desktop.
Кнопка, которая меняет цвет фона в момент нажатия
import UIKit
class ColorButton: UIButton {
let normalColor = UIColor.blue
let pressedColor = UIColor.green
override func awakeFromNib() {
super.awakeFromNib()
let normalBg = coloredImage(normalColor)
let pressedBg = coloredImage(pressedColor)
setBackgroundImage(normalBg, for: .normal)
setBackgroundImage(pressedBg, for: .selected)
setBackgroundImage(pressedBg, for: .highlighted)
}
private func coloredImage(_ color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment