使用 imageView.animationImages 属性对 UIButton 进行动画处理



我正在尝试为UIButton做一个简单的 2 帧动画。我知道使用 UIButton's imageView.animationImages 属性可以实现这一点 - 将其设置为数组并对其进行动画处理。但是当我这样做时,什么都没有出现。仅供参考,我已经检查了按钮图像数组,它确实包含我要显示的图像。有什么想法我哪里出错了吗?

NSArray *buttonImages = bookDoc.book.buttonImages;
UIImage *bookImage = bookDoc.thumbImage;
UIButton *bookButton = [UIButton buttonWithType:UIButtonTypeCustom];
bookButton.frame = CGRectMake(0, 0, bookImage.size.width, bookImage.size.height);
//[bookButton setBackgroundImage:bookImage forState:UIControlStateNormal];
bookButton.imageView.animationImages = buttonImages;
bookButton.imageView.animationDuration = 0.5;
bookButton.imageView.animationRepeatCount = INFINITY;
[bookButton addTarget:self action:@selector(bookButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[bookButton.imageView startAnimating];

UIButtonimageView用 (0,0,0,0( 的帧初始化,即它不可见(实际上也是隐藏的(。

您可以自行配置framehidden属性:

bookButton.imageView.frame = CGRectMake(0, 0, 20, 20);
bookButton.imageView.hidden = NO;

或者,更简单的是使用动画的第一个图像

[bookButton setImage:buttonImages[0] forState:UIControlStateNormal];

这将取消隐藏图像视图并设置其正确的框架。

一旦图像视图可见,它就会动画化。

我想

我从来没有尝试过将图像保存到按钮的imageView属性中。我一直使用 setImage:forState 或 setBackgroundImage:forState。

我的猜测是该按钮正在设置其图像视图本身的图像属性,使用(nil(图像作为默认图像状态。

您是否尝试过将button.imageView.image属性设置为静态图像以查看其是否有效? 正如我所说,我的猜测是,该按钮将覆盖您在 setImage:forState 中提供的设置提供的任何图像(如果您从未为当前状态提供图像,则为 nil。

我刚刚写了这个,它有效。它的缺点是我在 IB 中设置的突出显示的图像似乎不起作用。Xcode 5.也许禁用的图像等也不起作用。如果你不在乎这一点,这行得通。

+(void)animatemjad:(UIButton*)button offimagenames:(NSArray*)imagenames startdelay:(const NSTimeInterval)STARTDELAY {
    UIImageView* imageview = [button imageView];
    NSMutableArray* images = [NSMutableArray array];
    for (NSString* imagename in imagenames) {
        UIImage* image = [UIImage imageNamed:imagename];
        NSAssert(image != nil, @"Failed loading imagename: %@", imagename);
        if (image == nil)
            return; // return out here... whatever
        [images addObject:image];
    }
    imageview = [[UIImageView alloc] initWithImage:images.firstObject];
    [button addSubview:imageview];
    imageview.animationImages = images;
    imageview.animationDuration = 5;
    imageview.animationRepeatCount = 0;
    [imageview performSelector:@selector(startAnimating) withObject:nil afterDelay:STARTDELAY]; // [imageview startAnimating];
}

最新更新