You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS/Objective-C:实现UIBarButtonItem图片切换的淡入淡出动画

实现UIBarButtonItem自定义图片的淡入淡出切换动画

你的问题主要出在两个核心点上:一是错误地尝试直接修改UIBarButtonItem的图片(因为它是基于自定义UIButton创建的,必须操作这个按钮实例才能切换图片);二是在完成块里直接设置alpha为1,没有包裹在动画块中,所以没有淡入效果。下面给你两种可行的解决方案:

方案一:用系统过渡动画实现交叉淡入淡出(推荐)

这种方式最简洁,系统会自动处理两张图片的交叉过渡效果,不需要手动调整alpha值。

首先,你需要在ViewController中保存自定义按钮的引用(比如添加一个属性):

@property (nonatomic, strong) UIButton *menuButton;

然后在viewWillAppear中初始化按钮和BarButtonItem:

self.menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.menuButton setFrame:CGRectMake(12, 0, 22, 22)];
[self.menuButton addTarget:self action:@selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.menuButton setImage:[UIImage imageNamed:@"firstimage.png"] forState:UIControlStateNormal];
UIBarButtonItem *myBarButton = [[UIBarButtonItem alloc] initWithCustomView:self.menuButton];
// 根据你的需求设置为左/右BarButtonItem
self.navigationItem.leftBarButtonItem = myBarButton;

接下来在viewDidAppear中执行过渡动画:

[UIView transitionWithView:self.menuButton
                  duration:1.0
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    // 在动画块中切换按钮的图片
                    [self.menuButton setImage:[UIImage imageNamed:@"menu2.png"] forState:UIControlStateNormal];
                } completion:^(BOOL finished) {
                    // 动画完成后的回调,不需要的话可以留空
                }];

方案二:手动控制淡出+淡入动画

如果你想分开控制淡出和淡入的时长、延迟,可以用这种方式:

同样先保存menuButton的引用,然后在viewDidAppear中执行:

// 先让第一张图片淡出
[UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
    self.menuButton.alpha = 0;
} completion:^(BOOL finished) {
    if (finished) {
        // 淡出完成后切换图片
        [self.menuButton setImage:[UIImage imageNamed:@"menu2.png"] forState:UIControlStateNormal];
        // 再让第二张图片淡入
        [UIView animateWithDuration:0.5 animations:^{
            self.menuButton.alpha = 1;
        }];
    }
}];

为什么你的原代码不生效?

  • [self.myBarButton setImage:secondImage];无效:因为你的UIBarButtonItem是用自定义UIButton初始化的,setImage:方法只对系统默认样式的BarButtonItem生效,必须操作底层的UIButton实例来切换图片。
  • 直接设置alpha = 1无动画:只有把属性修改放在UIView animateWithDuration:的动画块中,系统才会生成过渡动画效果,即时设置属性是没有动画的。

内容的提问来源于stack exchange,提问作者user6631314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:24:26