You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
LeCountdown/LeCountdown/Views/Reusable/View+Extension.swift

64 lines
2.0 KiB

//
// View+Extension.swift
// LeCountdown
//
// Created by Laurent Morvillier on 16/02/2023.
//
import Foundation
import SwiftUI
extension View {
/// Focuses next field in sequence, from the given `FocusState`.
/// Requires a currently active focus state and a next field available in the sequence.
///
/// Example usage:
/// ```
/// .onSubmit { self.focusNextField($focusedField) }
/// ```
/// Given that `focusField` is an enum that represents the focusable fields. For example:
/// ```
/// @FocusState private var focusedField: Field?
/// enum Field: Int, Hashable {
/// case name
/// case country
/// case city
/// }
/// ```
func focusNextField<F: RawRepresentable>(_ field: FocusState<F?>.Binding) where F.RawValue == Int {
Logger.log("focusNextField")
guard let currentValue = field.wrappedValue else { return }
let nextValue = currentValue.rawValue + 1
if let newValue = F.init(rawValue: nextValue) {
field.wrappedValue = newValue
} else {
field.wrappedValue = nil
}
}
/// Focuses previous field in sequence, from the given `FocusState`.
/// Requires a currently active focus state and a previous field available in the sequence.
///
/// Example usage:
/// ```
/// .onSubmit { self.focusNextField($focusedField) }
/// ```
/// Given that `focusField` is an enum that represents the focusable fields. For example:
/// ```
/// @FocusState private var focusedField: Field?
/// enum Field: Int, Hashable {
/// case name
/// case country
/// case city
/// }
/// ```
func focusPreviousField<F: RawRepresentable>(_ field: FocusState<F?>.Binding) where F.RawValue == Int {
guard let currentValue = field.wrappedValue else { return }
let nextValue = currentValue.rawValue - 1
if let newValue = F.init(rawValue: nextValue) {
field.wrappedValue = newValue
} else {
field.wrappedValue = nil
}
}
}