我想使用扩展名创建UIView的副本,并复制其他变量。
要复制我正在使用的UIView :(来自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
}
}
要在UIView上添加变量,我正在使用: 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)
}
}
}
但是,在复制UIView时,它的子视图不会保持正确的切换状态。
有人得到一种不仅可以复制UIView而且可以保留扩展名中的变量的解决方案吗?
P.S。我不能使用子类作为解决方案