Here's some working code for custom view I wrote in few minutes, hope it helps. It creates 10 green layers, and animates them each second to different locations.
MBLineLayerDelegate *lineLayerDelegate;
@property (nonatomic, retain) NSMutableArray *ballLayers;
- (void)awakeFromNib
{
self.ballLayers = [NSMutableArray array];
lineLayerDelegate = [[MBLineLayerDelegate alloc] init];
for (NSUInteger i = 0; i < 10; i++) {
CALayer *ball = [CALayer layer];
CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
ball.frame = CGRectMake(x, y, 20, 20);
ball.backgroundColor = [UIColor greenColor].CGColor;
ball.delegate = lineLayerDelegate;
[self.layer addSublayer:ball];
[self.ballLayers addObject:ball];
}
[self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:0];
}
- (void)animateBallsToRandomLocation
{
for (CALayer *layer in self.ballLayers) {
CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
layer.position = CGPointMake(x, y);
}
[self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:1];
}
Here's some code for CALayer's delegate that draws a line:
@interface MBLineLayerDelegate : NSObject {
}
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx;
@end
@implementation MBLineLayerDelegate
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
CGRect rect = layer.bounds;
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetAllowsAntialiasing(context, YES);
CGContextSetShouldAntialias(context, YES);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, rect.size.width, rect.size.height);
CGContextRestoreGState(context);
}
@end