如何让SwiftUI Picker选中项文本强制显示在一行?
解决SwiftUI Picker选中项文本换行问题
我的Picker组件中部分选中项的文本会显示为两行,如何避免这种情况?
截图说明:Picker文本显示为两行的示意图
以下是我的代码:
struct PickerTestView: View { @AppStorage("firstNotificationSelection") var firstNotificationSelection: String = (UserDefaults.standard.string(forKey: "firstNotificationSelection")) ?? "None" @AppStorage("secondNotificationSelection") var secondNotificationSelection: String = (UserDefaults.standard.string(forKey: "secondNotificationSelection")) ?? "None" let notificationChoices: [String] = ["None", "At time of match", "5 minutes before...", "10 minutes before...", "30 minutes before...", "1 hour before...", "2 hours before..."] var body: some View { NavigationStack { Form { Section { Picker(selection: $firstNotificationSelection) { ForEach(notificationChoices, id: \.self) { choice in Text(choice) } } label: { Text("Alert") } if firstNotificationSelection != "None" { Picker(selection: $secondNotificationSelection) { ForEach(notificationChoices, id: \.self) { choice in Text(choice) } } label: { Text("Second alert") } } } } .navigationTitle("Notifications") .navigationBarTitleDisplayMode(.inline) } } }
我尝试使用.lineLimit(1)修饰符以及固定Picker的frame,但均无效果。
解决方案
在Form场景下的SwiftUI Picker,系统默认样式会约束文本容器宽度导致换行,以下几种方法可以解决:
给Picker内的Text添加
.fixedSize()
该修饰符会让文本保持固有尺寸,Picker会自动适配宽度避免换行,修改代码如下:ForEach(notificationChoices, id: \.self) { choice in Text(choice) .fixedSize() }切换Picker样式为
.navigationLinkPickerStyle()
这种样式下选中项会以单行展示,过长文本自动显示省略号,同时保留完整的选择界面:Picker(selection: $firstNotificationSelection) { ForEach(notificationChoices, id: \.self) { choice in Text(choice) } } label: { Text("Alert") } .pickerStyle(.navigationLinkPickerStyle())设置Picker的布局优先级
给Picker添加.layoutPriority(1),让它优先占用可用空间,避免文本被压缩换行:Picker(selection: $firstNotificationSelection) { ForEach(notificationChoices, id: \.self) { choice in Text(choice) } } label: { Text("Alert") } .layoutPriority(1)
注:.lineLimit(1)无效是因为Form中的Picker样式会强制约束文本容器宽度,上述方法能绕过这个限制。
内容的提问来源于stack exchange,提问作者simsab
相关产品推荐
相关产品推荐

