UIView重复

时间:2010-01-25 09:45:14

标签: ios objective-c uiview

我需要复制一个视图及其所有子视图。

有谁知道怎么做?

6 个答案:

答案 0 :(得分:24)

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

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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

以下是您可以使用的新方法:使用UIView的方法:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates

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

答案 3 :(得分:0)

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

Col A   Col B   Col C   Col D
         758             500
         123             750
         758             100

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

Col A   Col B   Col C
 123            Blue, quantity: 750
 444            Large, quantity: 100
 758            Pink, quantity: 500

Refrence from here.

答案 4 :(得分:0)

Swift版本

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

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

我的完整答案包括here

答案 5 :(得分:0)

enter image description here

您可以将自定义视图拖到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 <UIKit/UIKit.h>

@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