I can't find too many examples of the following issue so here I'm again asking for your help, on my app, I want my user be able to input on the textfield only time for example 22:30, the textfield have to accept only time not any kind of letter or other and moreover i need to make sure the user don't insert more than 4 digits is there any possible solution and how can I do that?
TextField("Test2", text: $test)
.textFieldStyle(.roundedBorder)
.keyboardType(.numberPad)
i have no idea what to look to solve this issue, some sort of formatter but i can only find the number formatter, noting related to time
thanks
struct TimeTextField: View {
@Binding var time: String
var body: some View {
TextField("Time", text: $time)
.textFieldStyle(.roundedBorder)
.textContentType(.none)
.keyboardType(.numberPad)
.onChange(of: time) { oldValue,newValue in
time = formatTimeInput(newValue)
}
}
private func formatTimeInput(_ input: String) -> String {
let allowedCharacterSet = CharacterSet(charactersIn: "0123456789")
// Remove non-numeric characters
let numericString = input.components(separatedBy: allowedCharacterSet.inverted).joined()
// Limit the input to 4 digits
let limitedString = String(numericString.prefix(4))
// Insert colons at appropriate positions (e.g., 2230 -> 22:30)
let formattedString: String
if limitedString.count > 2 {
let index = limitedString.index(limitedString.startIndex, offsetBy: 2)
let hour = limitedString[..<index]
let minute = limitedString[index...]
formattedString = "\(hour):\(minute)"
} else {
formattedString = limitedString
}
return formattedString
}
}
To restrict user input in a TextField to a specific format, such as allowing only time input with a maximum of 4 digits, you can utilize the TextField's textContentType property and validate the input using a custom formatter.
Handle with onReceive rather than on change*
.onReceive(NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification)) { _ in
time = formatTimeInput(time)
}