【问题标题】:SwiftUI Picker iOS 16 not filling available spaceSwiftUI Picker iOS 16 not filling available space
【发布时间】:2022-12-27 04:11:02
【问题描述】:

I am using the following code (example) to render a SwiftUI Picker on iOS:

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). This results in longer strings flowing onto multiple lines even when this isn't neccessary.

Short String (all fine):

Long String (not so good):

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. If I add a background to the Picker, it is clear that it only fills around 1/3 of the available space.

Does anyone have any suggestions?

【问题讨论】:

  • I have found a workaround which helps to some extent. Adding this to the Picker: .frame(maxWidth: .infinity, alignment: .trailing)

标签: ios iphone swiftui picker


【解决方案1】:

Separate the label from the Pickerandwrap it in a 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.
  2. Use the .fixedSize() modifier on the new Text. This will allow the Picker to expand to fit all its contents.
  3. Use Spacer between Text label and Picker to push both items to the edge.

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 2015-02-16
    • 2022-11-11
    • 2022-11-10
    • 2022-12-19
    • 1970-01-01
    • 2022-12-01
    • 2022-12-15
    • 2021-08-19
    相关资源
    最近更新 更多