iOS iPhone is it possible to clone UIView and have it draw itself to two UIViews?

后端 未结 4 1396
梦如初夏
梦如初夏 2020-12-15 08:05

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 i

4条回答
  •  遥遥无期
    2020-12-15 08:54

    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.

提交回复
热议问题