UIView重复

我需要复制一个视图,包含所有的子视图。

有谁知道怎么做?

最简单(但可能不是最快)的方法是将其存档到NSData对象中并立即取消归档。

NSData *tempArchive = [NSKeyedArchiver archivedDataWithRootObject:myView]; UIView *myViewDuplicate = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive]; 

要归档任何uiimage对象,只需将它们转换为一种或另一种imagerep(例如PNG)并归档该NSData对象,然后在unarchive中使用imageWithData恢复uiimage:

这是一个可以使用的新方法:使用UIView的方法:

 - (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 

这是绘制视图的最快方法。 适用于iOS 7。

可以通过归档和取消归档过程轻松复制UIView。

 NSData *tempArchive = [NSKeyedArchiver archivedDataWithRootObject:myView]; UIView *myViewDuplicate = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive]; 

但这忽略了UIImageView,所以对于UIImageView这样做,

 UIImage *img = [UIImage imageNamed: @"myImage"]; UIImage *img2 = [UIImage imageWithCGImage:img.CGImage scale:img.scale orientation:img.imageOrientation]; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:img2]; UIImage *imgCopy = [NSKeyedUnarchiver unarchiveObjectWithData:data]; NSLog(@"%@, %@", imgCopy, NSStringFromCGSize(imgCopy.size)); // -> , {50, 53} 

来自这里的参考。

Swift版本

这个答案显示了如何在Swift中做同样的事情,就像Objective-C中接受的答案一样。

 let tempArchive = NSKeyedArchiver.archivedDataWithRootObject(myView) let myViewDuplicate = NSKeyedUnarchiver.unarchiveObjectWithData(tempArchive) as! UIView 

我的完整答案有更多说明。

在此处输入图像描述

您可以将自定义视图拖到viewController的根视图之外。 在自定义视图类的实现中,重写enconde / decode方法。 实现IBOutlets和IBActions连接不会存档在内存中。

 @implementation MyCustomView -(MyCustomView*)aCopy{ NSData *temp = [NSKeyedArchiver archivedDataWithRootObject:self]; return [NSKeyedUnarchiver unarchiveObjectWithData:temp]; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:self.btnBack forKey:@"btnBack"]; [coder encodeObject:self.lbl1 forKey:@"lbl1"]; } -(instancetype)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; if (self) { self.btnBack = [aDecoder decodeObjectForKey:@"btnBack"]; self.lbl1 = [aDecoder decodeObjectForKey:@"lbl1"]; [_btnBack addTarget:self action:@selector(onBtnBack) forControlEvents:UIControlEventTouchUpInside]; } return self; } - (IBAction)onBtnBack{ //. . . 

MyCustomView.h:

 #import  @interface MyCustomView : UIView @property (weak, nonatomic) IBOutlet UILabel *lbl1; @property (weak, nonatomic) IBOutlet UIButton *btnBack; -(MyCustomView*)aCopy; @end 

在ViewController.m中重用自定义视图的示例:

 #import "ViewController.h" #import "MyCustomView.h" @interface ViewController () @property (strong, nonatomic) IBOutlet MyCustomView *myCustomView; @property (weak, nonatomic) IBOutlet UIView *vwPlaceHolder; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view addSubview:_myCustomView]; } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; MyCustomView *vwCopy = [_myCustomView aCopy]; vwCopy.lbl1.text = @"My other msg"; vwCopy.frame = _vwPlaceHolder.frame; [_vwPlaceHolder removeFromSuperview]; [self.view addSubview:vwCopy]; } @end