Skip to content

Instantly share code, notes, and snippets.

@thomasleese
Created October 13, 2018 12:20
Show Gist options
  • Select an option

  • Save thomasleese/17374afdb103aac93d2a803c7d23e3f5 to your computer and use it in GitHub Desktop.

Select an option

Save thomasleese/17374afdb103aac93d2a803c7d23e3f5 to your computer and use it in GitHub Desktop.
//
// ColouredCard.swift
// Abtastic
//
// Created by Thomas Leese on 12/10/2018.
// Copyright © 2018 Orycion. All rights reserved.
//
import UIKit
// MARK: - Looks and basic view.
@IBDesignable class ColouredCard: UIControl {
private let gradientLayer: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.cornerRadius = 10
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
return gradient
}()
@IBInspectable var gradientColour: UIColor = .clear {
didSet {
self.gradientLayer.colors = [
gradientColour.lighter.cgColor,
gradientColour.darker.cgColor,
]
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
private func setShadow() {
self.layer.shadowRadius = 8
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowOpacity = 0.4
self.layer.cornerRadius = 10
}
private func addGradient() {
self.layer.insertSublayer(self.gradientLayer, at: 0)
}
private func setupView() {
self.setShadow()
self.addGradient()
// default colour
self.gradientColour = .green
}
override func layoutSubviews() {
super.layoutSubviews()
self.gradientLayer.frame = self.bounds
}
}
// MARK: - Handle tapping animation.
extension ColouredCard {
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
UIView.animate(withDuration: 0.25) {
self.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}
return true
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
UIView.animate(withDuration: 0.25) {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
override func cancelTracking(with event: UIEvent?) {
UIView.animate(withDuration: 0.25) {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
}
// MARK: - Darker and lighter UIColors.
private extension UIColor {
var lighter: UIColor {
return self.changeBrightness { min($0 * 1.5, 1.0) }
}
var darker: UIColor {
return self.changeBrightness { $0 / 1.5 }
}
func changeBrightness(changer: (CGFloat) -> CGFloat) -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0
var b: CGFloat = 0, a: CGFloat = 0
guard getHue(&h, saturation: &s, brightness: &b, alpha: &a) else {
return self
}
return UIColor(
hue: h, saturation: s, brightness: changer(b), alpha: a
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment