代码之家  ›  专栏  ›  技术社区  ›  user6631314

ios/objective-c:在uibarbuttonitem中动画图像更改

  •  0
  • user6631314  · 技术社区  · 6 年前

    我正在尝试创建一个效果,其中uibarbuttonitem中的自定义图像更改为另一个图像。到目前为止,我已经能够用下面的代码得到第一个要分解的图像。有人能建议我如何让第二张图像同时淡入?

    //Create barbuttonitem in viewwillappear
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        [b setFrame:CGRectMake(12, 0, 22, 22)];
        [b addTarget:self action:@selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [b setImage:[UIImage imageNamed:@"firstimage.png"] forState:UIControlStateNormal];
        UIBarButtonItem * myBarButton = [[UIBarButtonItem alloc] initWithCustomView:b];
    
    //Animate in viewDidAppaer
    
     [UIView animateWithDuration:1.0
                              delay:1.0
                            options:UIViewAnimationOptionCurveEaseIn
                         animations:^{
                             self.myBarButton.customView.alpha = 0;
                         }
                         completion:^(BOOL finished) {
    UIImage *secondImage = [UIImage imageNamed:@"menu2.png"];
        [self.myBarButton setImage:secondImage];//THis does not change image
                                     self.myBarButton.customView.alpha = 1;//no animation
                                 }];
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Prasad Parab    6 年前

    你可以用这样的东西

    [UIView transitionWithView:self.myBarButton
                          duration:0.3
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^{ [self.myBarButton setImage:secondImage];}
                        completion:nil];
    
        2
  •  0
  •   Jigar    6 年前
    Try this code    
    
        @interface ViewController ()
            {
                UIBarButtonItem * myBarButton;
                NSTimer *time;
                UIButton *b;
            }
            @end
    
            @implementation ViewController
    
            - (void)viewDidLoad {
                [super viewDidLoad];
                b = [UIButton buttonWithType:UIButtonTypeCustom];
                [b setFrame:CGRectMake(12, 0, 22, 22)];
                [b addTarget:self action:@selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
                [b setImage:[UIImage imageNamed:@"AddPlus_Yellow.png"] forState:UIControlStateNormal];
                myBarButton = [[UIBarButtonItem alloc] initWithCustomView:b];
                self.navigationItem.rightBarButtonItem=myBarButton;
                time = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:@selector(onTick:) userInfo: nil repeats:NO];
                // Do any additional setup after loading the view, typically from a nib.
            }
    
            -(void)onTick:(NSTimer *)timer {
    
                [b setImage:[UIImage imageNamed:@"filter.png"] forState:UIControlStateNormal];
    [time invalidate];
    
            }