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

SwiftUI分组列表中DisclosureGroup内Picker文本过长布局异常

SwiftUI Picker长文本布局异常问题解决

在使用.grouped样式的SwiftUI List时,嵌入在DisclosureGroup内的Picker会出现长文本超出组件框架的布局异常。

问题代码

@ViewBuilder var categoryPicker: some View {
    Picker("Category", selection: $icon) {
        ForEach(category, id: \.self) { category in
            Text(category)
                .tag(category)
        }
    }
}

var body: some View {
    List {
        Section("Category") {
            DisclosureGroup("Create a category",
                            isExpanded: $isExpanded) {
                categoryNameTextField
                categoryPicker
                saveButton
            }
        }
        
        Section("Created category") {
            createdCategoryList
        }
    }
    .listStyle(.grouped)
}

问题截图

长文本超出Picker框架
展开后的异常布局

解决方法

方法1:允许文本自动换行

给Picker内的Text和Picker本身添加fixedSize修饰,让文本可以垂直换行,容器自适应高度:

@ViewBuilder var categoryPicker: some View {
    Picker("Category", selection: $icon) {
        ForEach(category, id: \.self) { category in
            Text(category)
                .tag(category)
                .fixedSize(horizontal: false, vertical: true)
        }
    }
    .fixedSize(horizontal: false, vertical: true)
}

方法2:自定义Picker列表项

通过HStack和Spacer确保文本在容器内换行,同时保持Picker的交互逻辑:

@ViewBuilder var categoryPicker: some View {
    Picker("Category", selection: $icon) {
        ForEach(category, id: \.self) { category in
            HStack {
                Text(category)
                    .lineLimit(nil)
                    .tag(category)
                Spacer()
            }
        }
    }
}

方法3:强制Picker占满可用宽度

给Picker添加frame(maxWidth: .infinity),让它充分利用父容器的宽度,避免文本溢出:

DisclosureGroup("Create a category", isExpanded: $isExpanded) {
    categoryNameTextField
    categoryPicker
        .frame(maxWidth: .infinity)
    saveButton
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:35:23