iOS iPhone is it possible to clone UIView and have

2019-01-23 05:47发布

I'm thinking of a way to have a UIView render itself onto another UIView as well as the first one. So I have my main UIView with it's bounds, and the UIView also renders itself in some other UIView.

Is this possible ? Does it require extensive layer operations?

4条回答
三岁会撩人
2楼-- · 2019-01-23 05:47

Create another instance of the UIView you wish to "clone" and add it as a subview to another view. You don't really clone a UIView object, you simply create another instance of it.

查看更多
疯言疯语
3楼-- · 2019-01-23 05:50

There is no easy way to clone a view and then to update two views by one line of code. Because their underlying CALayers are different. But for duplicating a UIView, here is a new method you can use: Use UIView's method:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates

This is the fastest way to draw a view. Available in iOS 7.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-23 06:02

Don't know whats your real intention is, but this will draw the view twice, userinteraction etc. will not work on the second view. Also this solution does not take care of different frame sizes.

Header of the View you want to clone

@interface SrcView : UIView
@property(nonatomic, readonly, strong) UIView *cloneView;
@end

@interface CloneView : UIView
@property(nonatomic, weak) UIView *srcView;
- (id)initWithView:(UIView *)src;
@end

implementation of the View you want to clone

#import "SrcView.h"
#import "CloneView.h"

@implementation SrcView
@synthesize cloneView;

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    [cloneView setNeedsDisplay];
}

- (UIView *)cloneView {
    if (!cloneView) {
        cloneView = [[CloneView alloc] initWithView:self];
    }
    return cloneView;
}

@end

@implementation CloneView
@synthesize srcView;

- (id)initWithView:(UIView *)src {
    self = [super initWithFrame:src.frame];
    if (self) {
        srcView = src;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    [srcView.layer renderInContext:UIGraphicsGetCurrentContext()];
}

@end

now you can just call cloneView and add it somewhere you want.

查看更多
三岁会撩人
5楼-- · 2019-01-23 06:07

This seems to be an oft asked question here on StackOverflow. For example:

iphone, ipad Duplicate UIView - Cloned View

Copying the drawn contents of one UIView to another

UIView duplicate

Duplicate, clone or copy UIView

But if it were me doing this, my first approach would be to get a handle to the UIView I want to copy, then recursively iterate all the subviews of it and then copy & add them as subviews to the UIView I want to copy the main UIView into.

I can't imagine there's too much layer operations going on with this, but you would likely need to figure out how to programmatically re-establish outlets and/or actions.

查看更多
登录 后发表回答