I want to create a copy of a UIView and also copy an additional variable, by using extensions.
To copy the UIView I'm using: (from Create a copy of a UIView in Swift)
extension UIView
{
func copyView<T: UIView>() -> T {
return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
}
}
To add a variable on UIView I'm using: https://marcosantadev.com/stored-properties-swift-extensions/
extension PropertyStoring {
func getAssociatedObject(_ key: UnsafeRawPointer!, defaultValue: T) -> T {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
}
enum ToggleState {
case on
case off
}
extension UIView: PropertyStoring {
typealias T = ToggleState
private struct CustomProperties {
static var toggleState = ToggleState.off
}
var toggleState: ToggleState {
get {
return getAssociatedObject(&CustomProperties.toggleState, defaultValue: CustomProperties.toggleState)
}
set {
return objc_setAssociatedObject(self, &CustomProperties.toggleState, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
However, when copying a UIView, it's subviews won't keep the correct toggle state.
Did anyone get a solution which can not only copy the UIView but also keep the variables from an extension?
P.S. I cannot use a subclass as a solution