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

SwiftUI视图在设备旋转及应用前后台切换时的对齐问题

解决方案

这个问题的核心是手动在tabItem中设置foregroundColor干扰了系统对TabBar布局的自动计算,尤其是在设备旋转、应用从后台恢复这类布局状态变化的场景下,系统无法正确同步TabBar元素的对齐逻辑。

修复步骤:

  1. 移除tabItem中手动设置的foregroundColor
  2. 通过UITabBarAppearance统一配置TabBar的选中/未选中状态样式(文字、图标颜色)

修改后的完整代码:

@main
struct SSWIFTUIApp: App {
    var body: some Scene {
        WindowGroup {
            TabbarViewApp()
        }
    }
}

struct TabbarViewApp: View {
    
    init() {
        let app = UITabBarAppearance()
        app.configureWithOpaqueBackground()
        app.backgroundColor = UIColor.systemPink
        app.selectionIndicatorTintColor = .black
        
        // 配置选中状态的文字和图标颜色
        let selectedAttrs: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.accentColor
        ]
        // 配置未选中状态的文字和图标颜色
        let unselectedAttrs: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.white
        ]
        
        app.stackedLayoutAppearance.selected.titleTextAttributes = selectedAttrs
        app.stackedLayoutAppearance.selected.iconColor = .accentColor
        app.stackedLayoutAppearance.normal.titleTextAttributes = unselectedAttrs
        app.stackedLayoutAppearance.normal.iconColor = .white
        
        UITabBar.appearance().standardAppearance = app
        if #available(iOS 15.0, *) {
            UITabBar.appearance().scrollEdgeAppearance = app
        }
    }
    
    @State private var selected: Int = 1
    @State private var id: String = ""
    
    var body: some View {
        TabView(selection: $selected) {
            NavigationView {
                VStack(alignment: .center, spacing: 0) {
                    TextField("Connection ID", text: $id)
                        .padding(.horizontal, 5)
                        .frame(height: 40)
                        .border(Color.black, width: 1)
                        .padding()
                }
            }
            .navigationViewStyle(.stack)
            .tabItem {
                Label("Home", systemImage: "house")
            }
            .tag(1)
            
            NavigationView {
                
            }
            .navigationViewStyle(.stack)
            .tabItem {
                Label("Settings", systemImage: "gear")
            }
            .tag(2)
        }
    }
}

额外说明:

  • 使用UITabBarAppearance的stackedLayoutAppearance(对应iOS默认的TabBar布局样式)来统一配置状态样式,让系统全权负责布局计算,避免手动样式带来的冲突
  • 确保standardAppearance和scrollEdgeAppearance(iOS15+)使用同一套配置,保证不同滚动状态下的样式一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:55:00