Hello, I have a situation where I want to format a TextField and simultaneously end input after reaching a certain number of characters.
For e.g. this is my view modifier which activate when user enter text of lenght
struct TextFieldLimitModifer: ViewModifier {
@Binding var value: String
var length: Int
func body(content: Content) -> some View {
content
.onChange(of: value) {
if value.count > length {
value = String($0.prefix(length))
}
}
}
}
And this is my formatter
public struct SortCodeFormatStyle: ParseableFormatStyle {
public init() {}
}
extension SortCodeFormatStyle {
public var parseStrategy: Self {
self
}
public func format(_ value: String) -> String {
value.chunks(ofCount: 2)
.joined(separator: "-")
}
}
extension SortCodeFormatStyle: ParseStrategy {
public func parse(_ value: String) -> String {
value.components(separatedBy: "-").joined()
}
}
extension FormatStyle where Self == SortCodeFormatStyle {
public static var sortCode: Self {
Self()
}
}
Interestingly, on iOS 17 devices, formatting is applied after reaching a certain number of characters, while on older iOS versions, the user can continue typing beyond that limit, and the text is truncated upon pressing submit.
And this becomes problematic, for example, when we have .keyboardType(.numberPad) and would like to enable this limit during input because we don't have a "done" button.
Are we supposed to do something here?