vds_ios/VDS/Components/Label/Label.swift
Matt Bruce ffe3641500 refactored out VDS from naming conventions
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2022-08-03 13:56:14 -05:00

94 lines
2.5 KiB
Swift

//
// VDSLabel.swift
// VDS
//
// Created by Matt Bruce on 7/28/22.
//
import Foundation
import UIKit
import VDSColorTokens
import Combine
open class Label: UILabel, ModelHandlerable, Initable {
@Published public var model: LabelModel = DefaultLabelModel()
private var cancellable: AnyCancellable?
@Proxy(\.model.fontSize)
public var fontSize: VDSFontSize
@Proxy(\.model.textPosition)
public var textPosition: VDSTextPosition
@Proxy(\.model.fontWeight)
public var fontWeight: VDSFontWeight
@Proxy(\.model.fontCategory)
public var fontCategory: VDSFontCategory
@Proxy(\.model.surface)
public var surface: Surface
//Initializers
required public convenience init() {
self.init(frame: .zero)
}
public required convenience init(with model: LabelModel) {
self.init()
self.model = model
set(with: model)
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
cancellable = $model.debounce(for: .seconds(Constants.ModelStateDebounce), scheduler: RunLoop.main).sink { [weak self] viewModel in
self?.onStateChange(viewModel: viewModel)
}
}
private func getTextColor(for disabled: Bool, surface: Surface) -> UIColor {
if disabled {
if surface == .light {
return VDSColor.elementsSecondaryOnlight
} else {
return VDSColor.elementsSecondaryOndark
}
} else {
if surface == .light {
return VDSColor.elementsPrimaryOnlight
} else {
return VDSColor.elementsPrimaryOndark
}
}
}
//functions
private func onStateChange(viewModel: LabelModel) {
text = viewModel.text
textAlignment = viewModel.textPosition.textAlignment
textColor = getTextColor(for: viewModel.disabled, surface: viewModel.surface)
guard let vdsFont = try? VDSFontStyle.font(for: viewModel.fontCategory, fontWeight: viewModel.fontWeight, fontSize: viewModel.fontSize) else {
font = VDSFontStyle.RegularBodyLarge.font
return
}
font = vdsFont
}
//Modelable
public func set(with model: LabelModel) {
self.model = model
}
}