vds_ios/VDS/Components/Icon/Icon.swift
Matt Bruce 31975f4e19 added customsize
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2023-05-02 09:21:00 -05:00

112 lines
3.3 KiB
Swift

//
// Icon.swift
// VDS
//
// Created by Matt Bruce on 1/9/23.
//
import Foundation
import UIKit
import VDSColorTokens
import Combine
@objc(VDSIcon)
open class Icon: View {
//--------------------------------------------------
// MARK: - Private Properties
//--------------------------------------------------
private var widthConstraint: NSLayoutConstraint?
private var heightConstraint: NSLayoutConstraint?
//--------------------------------------------------
// MARK: - Public Properties
//--------------------------------------------------
open var imageView = UIImageView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
open var color: Color = .black { didSet { didChange() }}
open var size: Size = .medium { didSet { didChange() }}
open var name: Name? { didSet { didChange() }}
open var customSize: Int? { didSet { didChange() }}
//functions
//--------------------------------------------------
// MARK: - Lifecycle
//--------------------------------------------------
open override func setup() {
super.setup()
addSubview(imageView)
imageView.pinToSuperView()
heightConstraint = imageView.heightAnchor.constraint(equalToConstant: size.dimensions.height)
heightConstraint?.isActive = true
widthConstraint = imageView.widthAnchor.constraint(equalToConstant: size.dimensions.width)
widthConstraint?.isActive = true
backgroundColor = .clear
isAccessibilityElement = true
accessibilityTraits = .image
}
open override func reset() {
super.reset()
color = .black
imageView.image = nil
}
//--------------------------------------------------
// MARK: - State
//--------------------------------------------------
open override func updateView() {
super.updateView()
//get the color for the image
var imageColor = color.value
//ensure the correct color for white/black colors
if surface == .dark && color == Color.black {
imageColor = VDSColor.elementsPrimaryOndark
} else if surface == .light && color == Color.black {
imageColor = VDSColor.elementsPrimaryOnlight
}
//set the icon dimensions
var dimensions = size.dimensions
if let customSize {
dimensions = .init(width: customSize, height: customSize)
}
heightConstraint?.constant = dimensions.height
widthConstraint?.constant = dimensions.width
//get the image name
//set the image
if let name, let image = getImage(for: name.rawValue) {
setImage(image: image, imageColor: imageColor)
} else {
imageView.image = nil
}
}
public override func updateAccessibilityLabel() {
}
private func getImage(for imageName: String) -> UIImage? {
return BundleManager.shared.image(for: imageName)
}
private func setImage(image: UIImage, imageColor: UIColor) {
imageView.image = image.withTintColor(imageColor)
}
}