SwiftUI - 选择器重叠

标签 swiftui picker

我正在尝试创建一个组件,它基本上是两个彼此相邻的 SwiftUI 选择器,如下所示:enter image description here

现在它只是一个 super 简单的实现:

@State var hourSelection = 0
@State var daySelection = 0

var days = [Int](0 ..< 30)
var hours = [Int](0 ..< 30)

...

GeometryReader { proxy in
  HStack(spacing: 0) {
    Picker(selection: self.$daySelection, label: Text("")) {
      ForEach(0 ..< self.days.count) { index in
        Text("\(self.days[index]) d").tag(index)
      }
    }
    .pickerStyle(.wheel)
    .frame(width: proxy.size.width / 2, height: proxy.size.height, alignment: .leading)

    Picker(selection: self.$hourSelection, label: Text("")) {
      ForEach(0 ..< self.hours.count) { index in
        Text("\(self.hours[index]) h").tag(index)
      }
    }
    .pickerStyle(.wheel)
    .frame(width: proxy.size.width / 2, height: proxy.size.height, alignment: .trailing)
  }
}

尝试使用左侧的选择器简单使用右侧的选择器。换句话说,它们重叠。如何使用 SwiftUI 解决此问题? Stack Overflow 上没有其他解决方案对我有用。

我看过Pickers are overlapping in ios 15 preventing some of them to be scrolled但公认的解决方案对我不起作用。

我尝试使用 .compositingGroup(),然后在 .frame() 之后使用 .clipped(),但这没有用,也没有应用 。 mask(Rectangle()) 到父容器。

更新:即使使用 iOS 16 更新和新的 XCode Beta,问题仍然存在。

最佳答案

另一种可能的变体 - 只是为了使底层 UIPickerView(因为它是问题的根源)是可压缩的:

使用 Xcode 13.4/iOS 15.5 测试

demo

extension UIPickerView {
    override open func didMoveToSuperview() {
        super.didMoveToSuperview()
        self.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    }
}

Test module on GitHub

关于SwiftUI - 选择器重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72370708/

相关文章:

ios - SwiftUI: View 从一个堆栈到另一个堆栈的动画移动?

swift - 当涉及协调器时,如何在 SwiftUI View 与另一个 View 之间进行通信?

swift - 在 SwiftUI 中处理 UITextView 的 UIResponder

ios - 使用基于之前选择的内容的选择器 View

ios - 检测选择器 View 的宽度和高度

swift - 表达式类型不明确,在 `ForEach` 中自定义类数组上没有更多上下文

webview - 如何在 SwiftUI View 中插入 iframe?

android - 如何将十六进制颜色代码 #RRGGBB 转换为 R、G、B 值

reactjs - react native 选择器选择 : How to auto-select an item but still be able to select others?

ios - 弹出窗口中的 CNContactPickerViewController (iOS)