簡體   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