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

SwiftUI中TabView的animation()遭弃用,如何改用指定动画API?

解决SwiftUI TabView动画API弃用问题

iOS 15之后,全局的.animation()修饰符被弃用,取而代之的是基于值触发的animation(_:value:)API,或者在修改状态时用withAnimation包裹操作。针对你的引导页场景,有两种可行方案:

方案1:使用animation(_:value:)修饰符

直接替换原来的全局动画修饰符,指定动画触发的依赖值为currentIndex——因为TabView的页面切换完全由这个状态变量驱动,只有当它变化时才需要触发动画。

修改后的完整代码:

VStack(spacing: 34) {
    TabView(selection: $currentIndex) {
        ForEach(viewModel.getOnBoards(), id: \.id) { onboard in
            OnBoardItemView(onBoard: onboard)
        }
    }
    .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    // 替换弃用的animation,绑定到currentIndex
    .animation(.easeInOut(duration: 1.0), value: currentIndex)
    .transition(.slide)
    
    Spacer()
    
    ItemIndicatorView(
        totalNumberOfItem: 3,
        current: $currentIndex
    )
    
    ControllerView(
        currentIndex: $currentIndex,
        totalNumberOfItem: 3,
        onboard: viewModel.getOnBoardItemAt(position: currentIndex-1)
    )
}

方案2:使用withAnimation包裹状态修改操作

如果你的页面切换是通过按钮点击等主动操作触发的(比如ControllerView里的下一步按钮),可以在修改currentIndex的地方用withAnimation包裹,这种方式更精准控制动画触发时机,此时TabView上不需要加任何animation修饰符。

示例(假设ControllerView内的下一步按钮逻辑):

// 点击下一步时的操作
Button("下一步") {
    withAnimation(.easeInOut(duration: 1.0)) {
        currentIndex += 1
    }
}

两种方案都能解决弃用警告,推荐方案1,因为它直接和TabView的状态绑定,逻辑更清晰,适配你的现有代码结构。

内容的提问来源于stack exchange,提问作者Aminul Haque Aome

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:55:25