0

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Leo
  • 19
  • 6
  • You can create a custom UIView subclass with the stored property you want and then try to copy that view. – Ratnesh Jain Jan 22 '19 at 11:08
  • @RatneshJain I should have mentioned I cannot use a subclass, added that in the question – Leo Jan 22 '19 at 11:43
  • If you are using NSKeyedArchiver your properties have to be encoded and decoded through encodeWithCoder and initWithCoder. – MartinM Jan 22 '19 at 12:12

0 Answers0