107 lines
2.8 KiB
Swift
107 lines
2.8 KiB
Swift
//
|
|
// Children.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 7/25/23.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
|
|
open class Children: View {
|
|
|
|
public enum Mode {
|
|
case textOnly
|
|
case viewOnly
|
|
case textViewOnly
|
|
|
|
public var errorMessage: String {
|
|
switch self {
|
|
case .textOnly:
|
|
return "Invalid type passed. Expected String."
|
|
case .viewOnly:
|
|
return "Invalid type passed. Expected a UIView."
|
|
case .textViewOnly:
|
|
return "Invalid type passed. Expected a UIView or String."
|
|
}
|
|
}
|
|
}
|
|
|
|
open var mode: Mode = .textViewOnly
|
|
|
|
open var child: Any? {
|
|
didSet {
|
|
updateChildView()
|
|
}
|
|
}
|
|
|
|
open var textStyle: TextStyle? {
|
|
didSet {
|
|
updateChildView()
|
|
}
|
|
}
|
|
|
|
open lazy var label: Label = {
|
|
let lbl = Label()
|
|
lbl.lineBreakMode = .byWordWrapping
|
|
lbl.numberOfLines = 0
|
|
lbl.layer.masksToBounds = true
|
|
lbl.textAlignment = .left
|
|
return lbl
|
|
}()
|
|
|
|
open var customSubview: UIView?
|
|
|
|
private func updateChildView() {
|
|
// Remove previous views if any
|
|
label.removeFromSuperview()
|
|
customSubview?.removeFromSuperview()
|
|
|
|
guard let child else { return }
|
|
|
|
var view: UIView? = nil
|
|
|
|
switch mode {
|
|
|
|
case .textOnly:
|
|
if let string = child as? String {
|
|
label.text = string
|
|
if let textStyle = textStyle {
|
|
label.textStyle = textStyle
|
|
}
|
|
view = label
|
|
}
|
|
case .viewOnly:
|
|
if let customView = child as? View {
|
|
customSubview = customView
|
|
view = customView
|
|
}
|
|
case .textViewOnly:
|
|
if let customView = child as? View {
|
|
customSubview = customView
|
|
view = customView
|
|
} else if let string = child as? String {
|
|
label.text = string
|
|
if let textStyle = textStyle {
|
|
label.textStyle = textStyle
|
|
}
|
|
view = label
|
|
}
|
|
}
|
|
|
|
guard let unwrappedView = view else {
|
|
print(mode.errorMessage)
|
|
return
|
|
}
|
|
|
|
addSubview(unwrappedView)
|
|
unwrappedView.translatesAutoresizingMaskIntoConstraints = false
|
|
NSLayoutConstraint.activate([
|
|
unwrappedView.topAnchor.constraint(equalTo: self.topAnchor),
|
|
unwrappedView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
|
|
unwrappedView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
|
|
unwrappedView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
|
|
])
|
|
}
|
|
}
|