简体   繁体   English

SwiftUI 拾取器 iOS 16 未填充可用空间

[英]SwiftUI Picker iOS 16 not filling available space

I am using the following code (example) to render a SwiftUI Picker on iOS:我正在使用以下代码(示例)在 iOS 上呈现一个 SwiftUI Picker

let strings: [String] = ["short", "very, ver long string"]
@State var selectedString: String = ""
Form {
   Picker("Method", selection: $selectedString) {
      ForEach(strings, id: \.self) { string in
         Text(string)
      }
   }
}

In iOS 16 the design of the menu style picker has changed (it now includes 2 small chevrons), which is all good, except it no longer fills the available width (as it did on iOS 15).在 iOS 16 中,菜单样式选择器的设计发生了变化(现在包括 2 个小 V 形),这一切都很好,只是它不再填充可用宽度(就像在 iOS 15 中所做的那样)。 This results in longer strings flowing onto multiple lines even when this isn't neccessary.这会导致更长的字符串流向多行,即使这不是必需的。

Short String (all fine):短字符串(都很好):

iOS 模拟器,在 SwiftUI 选择器的单行上显示一个短字符串

Long String (not so good):长字符串(不太好):

iOS 模拟器,在 SwiftUI 选择器的两行上显示更长的字符串

I have tried .fixedSize() , which works to some extend but if the string does in fact need to be on two lines this forces the label to be squished.我试过.fixedSize() ,它在一定程度上起作用但如果字符串实际上需要在两行上,这会强制 label 被压扁。 If I add a background to the Picker , it is clear that it only fills around 1/3 of the available space.如果我向Picker添加背景,很明显它只填充了大约 1/3 的可用空间。

Does anyone have any suggestions?有没有人有什么建议?

Separate the label from the Picker and wrap it in a HStack .将 label 与Picker分开并将其包装在HStack中。

Form {
    HStack {
        // the new label text
        Text("Method")
            .fixedSize() // give other views in HStack space to grow
        // push the external label and Picker to the leading and trailing view edges
        Spacer()
        Picker("Method", selection: $selectedString) {
            ForEach(strings, id: \.self) { string in
                Text(string)
            }
        }
        .labelsHidden() // the label is in the Text view
    }
}
  1. Hide the Picker label by using the .labelsHidden() modifier.使用.labelsHidden()修饰符隐藏Picker label。
  2. Use the .fixedSize() modifier on the new Text .在新的Text上使用.fixedSize()修饰符。 This will allow the Picker to expand to fit all its contents.这将允许Picker扩展以适应其所有内容。
  3. Use Spacer between Text label and Picker to push both items to the edge.Text label 和Picker之间使用Spacer将两个项目推到边缘。

带有短内容文本的 SwiftUI Picker 布局

具有较长内容文本的 SwiftUI Picker 布局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM