在 Swift 中创建 UIView 的副本 [英] Create a copy of a UIView in Swift
问题描述
因为对象是引用类型,而不是值类型,如果你设置一个 UIView
等于另一个 UIView
,视图是同一个对象.如果你修改一个,你也会修改另一个.
Because objects are reference types, not value types, if you set a UIView
equal to another UIView
, the views are the same object. If you modify one you'll modifying the other as well.
我有一个有趣的情况,我想在另一个视图中添加一个 UIView
作为子视图,然后我进行了一些修改,这些修改不应该影响原来的 UIView
代码>.如何制作 UIView
的副本,以便确保将该副本添加为子视图而不是对原始 UIView
的引用?
I have an interesting situation where I would like to add a UIView
as a subview in another view, then I make some modifications, and those modifications should not affect the original UIView
. How can I make a copy of the UIView
so I can ensure I add that copy as a subview instead of a reference to the original UIView
?
请注意,我无法以与创建原始视图相同的方式重新创建视图,我需要某种方式来创建给定任何 UIView
对象的副本.
Note that I can't recreate the view in the same way the original was created, I need some way to create a copy given any UIView
object.
推荐答案
你不能随意复制一个对象.只能复制实现了 NSCopying
协议的对象.
You can't arbitrarily copy an object. Only objects that implement the NSCopying
protocol can be copied.
但是,有一个解决方法:由于 UIView
可以序列化到磁盘(例如从 XIB 加载),您可以使用 NSKeyedArchiver
和 NSKeyedUnarchiver
创建一个序列化的 NSData
来描述你的视图,然后再次反序列化以获得一个独立但相同的对象.
However, there is a workaround: Since UIView
s can be serialized to disk (e.g. to load from a XIB), you could use NSKeyedArchiver
and NSKeyedUnarchiver
to create a serialized NSData
describing your view, then de-serialize that again to get an independent but identical object.
这篇关于在 Swift 中创建 UIView 的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!