一个解决方案看起来有点复杂,因为选取器不是本机SwiftUI控件,但后端有UIPickerView
个,所以我们需要将前面提到的to get rid of compression contains和to calculate most long label结合起来,并显式压缩选取器.
主要部分是
@State private var maxWidth = CGFloat.zero
@State private var width = CGFloat.infinity
var body: some View {
Picker("", selection: $selection) {
ForEach( ...
// Row/Label view is here
.background(GeometryReader {
Color.clear.preference(key: ViewWidthKey.self,
value: $0.frame(in: .local).size.width)
})
.onPreferenceChange(ViewWidthKey.self) {
self.maxWidth = max($0, maxWidth)
width = max($0, maxWidth)
}
}
}
.pickerStyle(.wheel)
.frame(maxWidth: width + 2 * 20 /* padding on both sides */)
}
使用Xcode 13.4/iOS 15.5测试