// // UIButton.swift // Wallet // // Created by Igor on 09.10.2020. // Copyright © 2020 List. All rights reserved. // import UIKit import WalletFoundation // MARK: - REFACTOR private class Button: UIButton { var action: () -> Void init(title: String? = nil, image: UIImage? = nil, action: @escaping () -> Void) { self.action = action super.init(frame: .zero) lzTitle = title setImage(image, for: .normal) sizeToFit() addTarget(self, action: #selector(onAction), for: .touchUpInside) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func onAction() { action() } } extension UIButton { static func button(image: UIImage, action: @escaping () -> Void) -> UIButton { Button(image: image, action: action) } } extension UIControl.State: CaseIterable { public static var allCases: [Self] = [.normal, .focused, .disabled, .selected, .reserved, .highlighted, .application] } extension UIButton { private struct Values { static var fontNamed = "fontNamed" static var lzTitle = "lzTitle" } @IBInspectable var fontNamed: String? { get { Common.Runtime.object(self, key: &Values.fontNamed) ?? "regular_14" } set { Common.Runtime.set(self, value: newValue, key: &Values.fontNamed);updateTitle() } } @IBInspectable var lzTitle: String? { get { Common.Runtime.object(self, key: &Values.lzTitle) } set { Common.Runtime.set(self, value: newValue, key: &Values.lzTitle);updateTitle() } } private func updateTitle() { UIControl.State.allCases.forEach { state in self.setTitle(nil, for: state) self.fontNamed >>- { font in self.setAttributedTitle(lzTitle?.localized.attributed(named: font, color: titleColor(for: state) ?? .clear), for: state) } } } } extension UIButton { func alignTextBelow(spacing: CGFloat = 6.0) { if let image = self.imageView?.image { let imageSize: CGSize = image.size self.titleEdgeInsets = UIEdgeInsets(top: spacing, left: -imageSize.width, bottom: -(imageSize.height), right: 0.0) self.titleLabel >>- { let labelString = NSString(string: $0.text ?? "") let titleSize = labelString.size(withAttributes: [NSAttributedString.Key.font: $0.font]) self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width) } } } } extension UIControl { func addAction(for controlEvents: UIControl.Event = .touchUpInside, _ closure: @escaping () -> Void) { @objc class ClosureSleeve: NSObject { let closure:() -> Void init(_ closure: @escaping() -> Void) { self.closure = closure } @objc func invoke() { closure() } } let sleeve = ClosureSleeve(closure) addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents) objc_setAssociatedObject(self, "\(UUID())", sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } }