animationuiviewcustom-draw

How to enable implicit animation in UIView when doing custom drawing?


I perform custom drawing in my UIView subclass using:

- (void)drawRect:(CGRect)rect;

How can I enable implicit animation when the drawing changes?


Solution

  • Since there were no other suggestions I went ahead with the layer delegate method. Perhaps that's the only option anyway.

    So in MyView I created a new CALayer property:

    -(CALayer*)stylesLayer
    {
    
        if (_stylesLayer == nil) {
    
            CALayer *aLayer = [CALayer layer];
            aLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
            if ([self respondsToSelector:@selector(setContentScaleFactor:)])
            {
                aLayer.contentsScale = self.contentScaleFactor;
            }
    
    
            _stylesLayer = aLayer;
            [_stylesLayer retain];
            [self.layer addSublayer:aLayer];
            [aLayer release];
        }
    
        return _stylesLayer;
    }
    

    And in MyViewController I implemented the delegate method that does the drawing:

    -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
    {
    
        // custom drawing code here
    
    }
    

    Now when a certain property changes I update the layer from MyViewController, which implicitly does a cross fade animation.

    -(void)setStyles:(NSArray *)styles
    {
    
        [styles retain];
        [_styles release];
        _styles = nil;
        _styles = styles;
    
        [self.myView.stylesLayer setNeedsDisplay];
    
    }