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

SwiftUI中Divider未正常显示问题排查求助

问题原因

你代码里把.navigationBarTitleDisplayMode(.inline)和.toolbar修饰在了ScrollView上,而非NavigationStack的根视图(外层VStack)。这会导致导航栏的布局逻辑干扰VStack内顶部Divider的显示,再加上默认Divider高度极细,很容易被导航栏背景覆盖,最终看不见。

解决方案

方案1:调整导航修饰符位置

把导航相关修饰符移到外层VStack上,明确布局边界:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) { // 去掉默认间距,避免分隔线和滚动视图间有空隙
                Divider()
                    .foregroundColor(Color.white.opacity(0.18))
                    .background(Color.white.opacity(0.18)) // 部分iOS版本需同时设background确保颜色生效
                ScrollView {
                    VStack {
                        // 示例内容,方便测试显示
                        Text("测试内容")
                            .foregroundColor(.white)
                            .padding(50)
                    }
                }
            }
            .background(Color("blue"))
            .navigationBarTitleDisplayMode(.inline) // 移到VStack上
            .toolbar { // 移到VStack上
                ToolbarItem(placement: .principal) {
                    Text("Title")
                        .foregroundColor(.white)
                }
            }
        }
    }
}

方案2:用自定义分隔线替代Divider

默认Divider样式不够可控的话,直接用Rectangle实现更稳妥:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // 自定义分隔线,明确高度和透明度
                Rectangle()
                    .fill(Color.white.opacity(0.18))
                    .frame(height: 1)
                ScrollView {
                    VStack {
                        Text("测试内容")
                            .foregroundColor(.white)
                            .padding(50)
                    }
                }
            }
            .background(Color("blue"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .principal) {
                    Text("Title")
                        .foregroundColor(.white)
                }
            }
        }
    }
}
补充提示
  • 部分iOS版本中,Divider的foregroundColor可能不生效,加个background就能解决。
  • 设置VStack(spacing: 0)能让分隔线和下方滚动视图紧密贴合,更符合设计图效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:05:10