繁体   English   中英

SwiftUI 选择器值在超过最大值时重置

[英]SwiftUI picker value to reset if it goes beyond max

我有一个定制的 SwiftUI 选择器。 选择器需要两件事:小时和分钟。 我的结构有一个名为 maxDurationSeconds 的值。 我的目标是,如果用户选择小时和分钟的组合,这使得整体 go 高于 maxDurationSeconds,我想将小时和分钟都重置为零。

var body: some View {
    let hours = [Int](0...maxHours)
    let minutes = [Int](0...maxMinutes)
    GeometryReader { geometry in
        HStack(spacing: 0) {
            Picker(selection: self.selection.hours, label: Text("")) {
                ForEach(0..<maxHours, id: \.self) { index in
                    Text("\(hours[index]) hr")
                        .foregroundColor(Color(Asset.Color.V2.white.color))
                }
            }
            .pickerStyle(.wheel)
            .frame(width: geometry.size.width / 2, height: geometry.size.height, alignment: .center)
            Picker(selection: self.selection.minutes, label: Text("")) {
                ForEach(0..<maxMinutes, id: \.self) { index in
                    Text("\(minutes[index]) min")
                        .foregroundColor(Color(Asset.Color.V2.white.color))
                }
            }
            .pickerStyle(.wheel)
            .frame(width: geometry.size.width / 2, height: geometry.size.height, alignment: .center)
        }
    }
}

由于文件很大,因此省略了结构的 rest。 但这里有必要的信息:我们从选择中得到一个绑定,其中包含小时和分钟。 MaxHours 和 maxMinutes 分别为 24 和 60。

这就是我想要实现的目标:

    let hoursInSeconds = selection.hours.wrappedValue
    let minutesInSeconds = selection.minutes.wrappedValue
    if(hoursInSeconds + minutesInSeconds > Int(maxDurationSeconds)) {
        selection.hours.wrappedValue = 0
        selection.minutes.wrappedValue = 0
    }

我不确定在哪里包含此代码。 我尝试对选择器视图进行点击手势并执行此操作,但它不会更新它们。 非常感谢任何反馈。

它可以通过改变selection来完成,比如

GeometryReader { geometry in
    HStack(spacing: 0) {
      // ... content 
    }
    .onChange(of: selection) { _ in // << assuming you confirm it to Equatable
   // .onChange(of: [selection.hours, selection.minutes]) { _ in // << alternate
         if(selection.hours + selection.minutes > Int(maxDurationSeconds)) {
           selection.hours = 0
           selection.minutes = 0
        }
    }
}

暂无
暂无

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

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