在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 $的引用C $ C>?
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的副本
object。
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.
但是,有一种解决方法:自<$ c $ c> UIView s可以序列化为磁盘(例如从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屋!