Ios 如何为UIControl/ui按钮设置从一种状态到另一种状态的动画转换?

Ios 如何为UIControl/ui按钮设置从一种状态到另一种状态的动画转换?,ios,uibutton,uicontrol,Ios,Uibutton,Uicontrol,我有一个UIButton,可以在突出显示时更改图像。从UIControlStateHighlight转换到UIControlStateNormal时,我希望高亮显示的图像慢慢淡入正常图像。有没有一个简单的方法可以做到这一点 我最终将UIButton子类化。下面是实现文件代码。我拿出了一些特定于应用程序的东西,所以我没有测试这段代码,但应该可以: #import "SlowFadeButton.h" @interface SlowFadeButton () @property(strong,

我有一个UIButton,可以在突出显示时更改图像。从UIControlStateHighlight转换到UIControlStateNormal时,我希望高亮显示的图像慢慢淡入正常图像。有没有一个简单的方法可以做到这一点

我最终将UIButton子类化。下面是实现文件代码。我拿出了一些特定于应用程序的东西,所以我没有测试这段代码,但应该可以:

#import "SlowFadeButton.h"

@interface SlowFadeButton ()

@property(strong, nonatomic)UIImageView *glowOverlayImgView; // Used to overlay glowing animal image and fade out

@end

@implementation SlowFadeButton



-(id)initWithFrame:(CGRect)theFrame mainImg:(UIImage*)theMainImg highlightImg:(UIImage*)theHighlightImg
{
    if((self = [SlowFadeButton buttonWithType:UIButtonTypeCustom])) {

        self.frame = theFrame;

        if(!theMainImg) {
            NSLog(@"Problem loading the main image\n");
        }
        else if(!theHighlightImg) {
            NSLog(@"Problem loading the highlight image\n");
        }

        [self setImage:theMainImg forState:UIControlStateNormal];
        self.glowOverlayImgView = [[UIImageView alloc] initWithImage:theHighlightImg];
        self.glowOverlayImgView.frame = self.imageView.frame;
        self.glowOverlayImgView.bounds = self.imageView.bounds;

        self.adjustsImageWhenHighlighted = NO;
    }

    return self;
}


-(void)setHighlighted:(BOOL)highlighted
{
    // Check if button is going from not highlighted to highlighted
    if(![self isHighlighted] && highlighted) {
        self.glowOverlayImgView.alpha = 1;
        [self addSubview:self.glowOverlayImgView];
    }
    // Check if button is going from highlighted to not highlighted
    else if([self isHighlighted] && !highlighted) {
        [UIView animateWithDuration:1.0f
                         animations:^{
                             self.glowOverlayImgView.alpha = 0;
                         }
                         completion:NULL];
    }

    [super setHighlighted:highlighted];
}

-(void)setGlowOverlayImgView:(UIImageView *)glowOverlayImgView
{
    if(glowOverlayImgView != _glowOverlayImgView) {
        _glowOverlayImgView = glowOverlayImgView;
    }

    self.glowOverlayImgView.alpha = 0;
}

@end
您也可以从
[self-imageForState:UIControlStateHighlighted]
中提取高亮显示的图像,并使用该图像,它应该也可以工作。主要是确保
adjustsImageWhenHighlighted=NO
,然后覆盖
setHighlighted:
方法