Skip to content

Applies a transformation to characters as they're typed into a SwiftUI TextField or TextEditor, while managing its cursor position.

Notifications You must be signed in to change notification settings

netceteragroup/SwiftUI-TransformingTextField

Repository files navigation

SwiftUI-TransformingTextField

I love SwiftUI! ❤️

While it simplifies the way we build apps, it (currently) has some limitations and even some strange quirks. For example, manipulating a TextField's text during editing causes the cursor to jump uncontrollably, and you really don't want to expose your users to that kind of madness. 🤪

Enter...

TransformingTextFieldModifier

docs/demo1.gif

TransformingTextFieldModifier applies a transformation to characters as they're typed into a TextField. It uses view introspection (thanks to SwiftUI-Introspect) to find the underlying UITextField (so it can even be applied to custom UIViewRepresentables that wrap a UITextField). 🎁

It can be used via convenient View extensions, which can be combined:

TextField(...)
    .transformingChanges(in: $text) { text, range, replacement in
        replacement.filter(\.isLetter)
    }
    .uppercased(text: $text)
    .characterLimit(6, in: $text)

New in 1.1.0

Added support for TextEditor and TextField with vertical axis on iOS 16 (both backed by a UITextView).

TransformingTextFieldDelegate

TransformingTextFieldDelegate is a UITextFieldDelegate that takes over the task of updating the text field's text, applying the given transformation to any text changes, and preserving the cursor's logical position.

More importantly, this works around SwiftUI's current undesirable behavior of throwing the cursor to the end of the field whenever the text buffer is modified programmatically.

Installation

Add https://github.com/netceteragroup/SwiftUI-TransformingTextField.git to your Swift package dependencies and import TransformingTextField.

For a quick demo, try the SwiftUI preview in TransformingTextField.swift. You can also run it by dropping TransformingTextField_Previews.Example() into your ContentView while in DEBUG mode.

var body: some View {
    TransformingTextField_Previews.Example()
}

SwiftUI-TransformingTextField was created by Vikram Kriplaney in July 2023.

About

Applies a transformation to characters as they're typed into a SwiftUI TextField or TextEditor, while managing its cursor position.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages