// // CommonViewRadioGroup.swift // Wallet // // Created by Igor on 27.02.2021. // Copyright © 2021 AM. All rights reserved. // import UIKit class CommonViewRadioGroup: CommonControlCustom { @IBOutlet private weak var stackView: UIStackView! @IBInspectable var titleStyle: String = "regular_14" @IBInspectable var isHorizontal: Bool = false { didSet { reload() } } var collection = [String]() { didSet { reload() } } var selectedIndex = 0 { didSet { update() } } override func setup() { super.setup() backgroundColor = .clear } private func reload() { stackView.arrangedSubviews.forEach({ $0.removeFromSuperview() }) stackView.axis = isHorizontal ? .horizontal : .vertical stackView.spacing = isHorizontal ? 22 : 12 collection.enumerated().forEach({ let btn = UIButton() btn.tag = $0.offset btn.contentHorizontalAlignment = .left btn.contentEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 10) btn.titleEdgeInsets = .init(top: 0, left: 5, bottom: 0, right: 0) btn.imageEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: 5) btn.setAttributedTitle(($0.element + " ").attributed(named: titleStyle, color: Asset.textGranite.color), for: .normal) btn.setAttributedTitle(($0.element + " ").attributed(named: titleStyle, color: Asset.textDeepWater.color), for: .highlighted) btn.setAttributedTitle(($0.element + " ").attributed(named: titleStyle, color: Asset.textDeepWater.color), for: .selected) btn.setImage(Asset.commonRadioNormal.image, for: .normal) btn.setImage(Asset.commonRadioSelected.image, for: .selected) btn.addTarget(self, action: #selector(onAction(_:)), for: .touchUpInside) stackView.addArrangedSubview(btn) }) (superview ?? self).layoutIfNeeded() update() } private func update() { stackView.arrangedSubviews.compactMap({ $0 as? UIButton }).enumerated().forEach({ $0.element.isSelected = $0.offset == selectedIndex }) } @objc private func onAction(_ btn: UIButton) { selectedIndex = btn.tag sendActions(for: .valueChanged) } }