Caps-iOS/CapCollector/View Components/RoundedButton.swift

100 lines
2.7 KiB
Swift
Raw Normal View History

2018-08-16 11:18:27 +02:00
//
// RoundedButton.swift
// CapFinder
//
// Created by User on 01.02.18.
// Copyright © 2018 User. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class RoundedButton: UIButton {
@IBInspectable var borderColor: UIColor = UIColor.black {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
//Normal state bg and border
@IBInspectable var normalBorderColor: UIColor? {
didSet {
layer.borderColor = normalBorderColor?.cgColor
}
}
@IBInspectable var normalBackgroundColor: UIColor? {
didSet {
setBgColorForState(color: normalBackgroundColor, forState: [])
}
}
//Highlighted state bg and border
@IBInspectable var highlightedBorderColor: UIColor?
@IBInspectable var highlightedBackgroundColor: UIColor? {
didSet {
setBgColorForState(color: highlightedBackgroundColor, forState: .highlighted)
}
}
private func setBgColorForState(color: UIColor?, forState: UIControl.State){
self.backgroundColor = color
// if color != nil {
// self.backgroundColor = color!
// setBackgroundImage(UIImage.imageWithColor(color: color!), for: forState)
// } else {
// setBackgroundImage(nil, for: forState)
// }
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = layer.frame.height / 2
// layer.cornerRadius = min(layer.frame.height, layer.frame.width) / 2
clipsToBounds = true
if borderWidth > 0 {
if state == [] && layer.borderColor == normalBorderColor?.cgColor {
layer.borderColor = normalBorderColor?.cgColor
} else if state == .highlighted && highlightedBorderColor != nil {
layer.borderColor = highlightedBorderColor!.cgColor
}
}
}
}
extension RoundedButton {
func set(template: String, with tint: UIColor) {
self.setImage(UIImage.templateImage(named: template), for: .normal)
self.tintColor = tint
self.borderColor = tint
}
}
//Extension Required by RoundedButton to create UIImage from UIColor
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 1.0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}