将CAAnimation添加到UITableViewCell中的子层

时间:2013-09-19 22:10:56

标签: ios core-animation calayer

我有一个带有imageView属性的uitableviewcell子类。我从网上获取图像,当我得到它时,我想将它交叉淡入到图像视图中。

我已经获得了我最初在视图控制器中使用的CAAnimation代码来应用此效果。我的代码看起来像这样:

    CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    [self.photoView.layer addAnimation:transition forKey:someKey];

现在,我想将该代码移到我的UITableViewCell中。我已尝试在不同的位置应用该动画,但它似乎没有影响。我把它放在awakeFromNib(单元格来自nib文件)以及willMoveToSuperview中。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

David是对的,您实际上并未更改代码中imageView的内容。

我刚刚创建了UITableViewCell的子类并将其添加到基本的iOS Single View应用程序中:

#import "AnimatedCell.h"

@implementation AnimatedCell {
    BOOL imageWasGrabbed;
}

- (id)initWithStyle:(UITableViewCellStyle)style 
    reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.frame = CGRectMake(0,0,320,44);
        self.imageView.image = [UIImage imageNamed:@"localImage"];
        self.textLabel.text = @"Locally loaded image";
        self.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return self;
}

-(void)grabImage {
    NSString *path = @"http://www.c4ios.com/images/temp/webImage@2x.png";
    NSURL *webImageUrl = [NSURL URLWithString:path];
    NSData *webImageData = [NSData dataWithContentsOfURL:webImageUrl];
    UIImage *image = [UIImage imageWithData:webImageData];

    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.delegate = self;
    NSString *n = kCAMediaTimingFunctionEaseInEaseOut;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:n];
    transition.type = kCATransitionFade;

    [self.imageView.layer addAnimation:transition forKey:@"animateContents"];

    self.imageView.image = image;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(!imageWasGrabbed) {
        [self grabImage];
    }
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    self.textLabel.text = @"Web loaded image";
    imageWasGrabbed = YES;
}

@end

将过渡添加到单元格的imageView图层后,需要调用以下内容:

self.imageView.image = image;

作为参考,我的项目的View Controller如下所示:

#import "ViewController.h"
#import "AnimatedCell.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    AnimatedCell *cell = [[AnimatedCell alloc]
                          initWithStyle:UITableViewCellStyleDefault
                          reuseIdentifier:@"AnimatedCell"];
    cell.center = self.view.center;
    [self.view addSubview:cell];
}

@end