UIView可以复制吗?
简单地使用这种方式:
UIView* view2 = [view1 copy]; // view1 existed
这将导致模拟器无法启动此应用程序。
尝试保留,
UIView* view2 = [view1 retain]; // view1 existed
// modify view2 frame etc
对 view2
的任何修改都将应用于 view1
,我知道 view2
与 view1
共享相同的内存。
为什么UIView
无法复制?原因是什么?
Simply using this way:
UIView* view2 = [view1 copy]; // view1 existed
This will cause simulator can not launch this app.
Try retain,
UIView* view2 = [view1 retain]; // view1 existed
// modify view2 frame etc
Any modifications to view2
will apply to view1
, I understand that view2
share same memory with view1
.
Why can't UIView
be copied? What is the reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这可能对您有用...存档视图,然后立即取消存档。这应该会给你一个视图的深层副本:
this might work for you ... archive the view and then unarchive it right after. This should give you a deep copy of a view:
您的应用程序可能会因以下内容而崩溃:
原因是 UIView 没有实现复制协议,因此 UIView 中没有
copyWithZone
选择器。Your app probably crashes with something like:
The reason is that UIView does not implement the copying protocol, and therefore there is no
copyWithZone
selector in UIView.您可以制作 UIView 扩展。在下面的示例 swift 代码片段中,函数 copyView 返回一个 AnyObject,因此您可以复制 UIView 的任何子类,即 UIImageView。
如果您只想复制 UIView,您可以将返回类型更改为 UIView。
用法示例:
You can make an UIView extension. In example swift snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView.
If you want to copy only UIViews you can change the return type to UIView.
Example usage:
对于 swift3.0.1:
for swift3.0.1:
UIView
没有实现NSCoping
协议,请参阅 UIView.h 中的声明:@interface UIView : UIResponder
因此,如果我们想要有一个类似
copy
的方法,我们需要实现NSCoping
协议一个类别左右。UIView
doesn't implement theNSCoping
protocol, see the declaration in UIView.h:@interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusEnvironment>
So, if we want to have a
copy
like method, we need to implement theNSCoping
protocol in a category or so.您可以将方法设置为如下所示:
然后您可以将 ivar 设置为返回值并保留它,如下所示:
You can make method something like this:
Then you can set your ivar to the return value and retain it like so: