You need to enable JavaScript to run this app. 选中UITabBarViewController的标签时能否添加Lottie动画?
优惠活动
大模型
产品
解决方案
定价
更多

选中UITabBarViewController的标签时能否添加Lottie动画?

标签栏选中时触发Lottie动画实现指引

以下是主流移动端平台的实现方案,可直接按对应步骤操作:

iOS(Swift 实现)

  • 先通过CocoaPods或SPM引入lottie-ios依赖
  • 自定义UITabBarController,提前创建和tab数量一一对应的LottieAnimationView数组,添加到tabBar的对应位置,默认设置isHidden = true,动画loopMode设为.playOnce
  • 实现UITabBarController代理方法tabBarController(_:didSelect:),在方法内处理动画逻辑:
    隐藏所有tab对应的Lottie视图、停止未完成动画,获取当前选中的tab索引,展示对应Lottie视图并调用play()触发动画,动画结束后可按需选择是否隐藏视图或保持最后一帧状态
    核心代码示例:
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    guard let selectedIndex = tabBarController.viewControllers?.firstIndex(of: viewController) else { return }
    // 重置所有Lottie视图状态
    lottieViews.forEach { $0.isHidden = true; $0.stop() }
    // 触发选中项动画
    let currentLottie = lottieViews[selectedIndex]
    currentLottie.isHidden = false
    currentLottie.play { [weak currentLottie] _ in
        // 动画结束后需要隐藏视图可取消下面的注释
        // currentLottie?.isHidden = true
    }
}

Android(Kotlin 实现)

  • 在模块级build.gradle中引入com.airbnb.android:lottie依赖
  • 自定义BottomNavigationView,或在布局中给每个menu项预留LottieAnimationView占位,默认设置visibility = GONE
  • 给BottomNavigationView设置OnItemSelectedListener监听,选中item时先隐藏所有Lottie视图、取消未完成动画,再展示选中项对应的Lottie视图并调用playAnimation()触发播放
    核心代码示例:
bottomNavigationView.setOnItemSelectedListener { menuItem ->
    val selectedIndex = getMenuItemIndex(menuItem)
    // 重置所有Lottie视图状态
    lottieViewList.forEach { 
        it.visibility = View.GONE
        it.cancelAnimation() 
    }
    // 播放选中项动画
    val targetLottie = lottieViewList[selectedIndex]
    targetLottie.visibility = View.VISIBLE
    targetLottie.playAnimation()
    true
}

Flutter 实现

  • 在pubspec.yaml中引入lottie依赖
  • 自定义BottomNavigationBar的item结构,用Stack布局包裹静态图标和Lottie组件,默认只展示静态图标
  • 在BottomNavigationBar的onTap回调中更新当前选中索引,触发组件重绘,选中状态时展示Lottie组件并设置为单次播放
    核心代码示例:
int _currentIndex = 0;

@override
Widget build(BuildContext context) {
  return Scaffold(
    bottomNavigationBar: BottomNavigationBar(
      currentIndex: _currentIndex,
      onTap: (index) {
        setState(() => _currentIndex = index);
      },
      items: List.generate(tabCount, (index) {
        return BottomNavigationBarItem(
          icon: _currentIndex == index 
            ? Lottie.asset('你的lottie文件本地路径', repeat: false)
            : Icon(对应tab的静态图标),
          label: 'Tab名称'
        );
      }),
    ),
  );
}

通用注意事项

  • 提前优化Lottie动画文件大小,避免文件过大导致切换卡顿
  • 非特殊需求建议将动画设置为单次播放,避免持续动画干扰用户操作
  • 保证Lottie视图尺寸和原标签图标尺寸完全一致,避免切换时出现位置偏移

内容的提问来源于stack exchange,提问作者Nawin P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:06:00