简体   繁体   English

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

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

I have a custom SwiftUI picker.我有一个定制的 SwiftUI 选择器。 The picker takes two things: hour and minute.选择器需要两件事:小时和分钟。 My struct has a value called maxDurationSeconds.我的结构有一个名为 maxDurationSeconds 的值。 My goal is, if the user selects a combination of hour and minute, which makes the overall go above the maxDurationSeconds, I want to reset both hour and minute to zero.我的目标是,如果用户选择小时和分钟的组合,这使得整体 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)
        }
    }
}

The rest of the struct is omitted since the file is huge.由于文件很大,因此省略了结构的 rest。 But here is the necessary info: We are getting a binding from selection, which has hour and minute in it.但这里有必要的信息:我们从选择中得到一个绑定,其中包含小时和分钟。 MaxHours and maxMinutes are 24 and 60. MaxHours 和 maxMinutes 分别为 24 和 60。

This is what I am trying to achieve:这就是我想要实现的目标:

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

I am not sure where to include this code.我不确定在哪里包含此代码。 I tried doing on tap gesture of the picker views and doing this, but it would not update them.我尝试对选择器视图进行点击手势并执行此操作,但它不会更新它们。 Any feedback is greatly appreciated.非常感谢任何反馈。

It can be done on change of selection , like它可以通过改变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