Files
2021-10-07 11:39:02 +00:00

104 lines
3.5 KiB
Swift

//
// Button.swift
// PrivadoVPN
//
// Created by Zhandos Bolatbekov on 03.06.2021.
// Copyright © 2021 Privado LLC. All rights reserved.
//
import UIKit
class Button: UIButton {
typealias TouchAction = () -> Void
// MARK: - Properties
var cornerRadius: CGFloat = 12.0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
}
}
var touchUpInside: TouchAction?
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
self.addTarget(self, action: #selector(self.touchUpInside(sender:)), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTarget(self, action: #selector(self.touchUpInside(sender:)), for: .touchUpInside)
}
convenience init(
frame: CGRect = .zero,
icon: UIImage? = nil,
pressedIconColor: UIColor? = nil,
text: String? = nil,
textColor: UIColor? = .blue,
pressedTextColor: UIColor? = nil,
font: UIFont = .systemFont(ofSize: 17),
backgroundColor: UIColor = .clear,
pressedColor: UIColor? = nil,
disabledColor: UIColor? = nil,
cornerRadius: CGFloat = 0,
borderWidth: CGFloat = 0,
borderColor: UIColor = .clear
) {
self.init(frame: frame)
let allControllStates: [UIControl.State] = [
.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved
]
for state in allControllStates {
let text = text ?? ""
let attributedTitle = NSMutableAttributedString(string: text)
attributedTitle.addAttribute(.foregroundColor, value: textColor ?? .blue, range: text.getNSRange(of: text))
if let icon = icon {
let textAttachment = NSTextAttachment()
let iconRect = CGRect(
x: 0,
y: (font.capHeight - icon.size.height).rounded() / 2,
width: icon.size.width,
height: icon.size.height
)
textAttachment.bounds = iconRect
textAttachment.image = icon.withRenderingMode(.alwaysTemplate)
attributedTitle.append(NSAttributedString(string: " "))
attributedTitle.append(NSAttributedString(attachment: textAttachment))
}
self.setAttributedTitle(attributedTitle, for: state)
}
self.setTitleColor(textColor, for: .normal)
if let pressedTextColor = pressedTextColor {
self.setTitleColor(pressedTextColor, for: .highlighted)
}
self.titleLabel?.adjustsFontSizeToFitWidth = true
self.titleLabel?.font = font
self.backgroundColor = backgroundColor
if let disabledColor = disabledColor {
setBackgroundImage(UIImage(ofColor: disabledColor), for: .disabled)
}
if let pressedColor = pressedColor {
setBackgroundImage(UIImage(ofColor: pressedColor), for: .highlighted)
}
self.layer.borderColor = borderColor.cgColor
self.layer.borderWidth = borderWidth
self.layer.cornerRadius = cornerRadius
self.clipsToBounds = cornerRadius > 0
self.cornerRadius = cornerRadius
self.translatesAutoresizingMaskIntoConstraints = false
}
// MARK: - Private
@objc
private func touchUpInside(sender: Button) {
self.touchUpInside?()
}
}