UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Selecting the content of a field on Entering a TextField

Forums > 100 Days of SwiftUI

As I was working on my project, I realized that "deleting the contents of the field" on entry was cumbersome, so I looked into how to select the field when I clicked into it. It wasn't all that easy. This may not be the right way.

This package https://github.com/siteline/SwiftUI-Introspect.git

Allowed me to make it happen.

private class TextFieldObserver: NSObject {
    @objc
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.selectAll(nil)
    }
}

private let textFieldObserver = TextFieldObserver()
    var body: some View {
            TextField(name, text: field )
                .introspectTextField { textField in
                                textField.addTarget(
                                    self.textFieldObserver,
                                    action: #selector(TextFieldObserver.textFieldDidBeginEditing),
                                    for: .editingDidBegin
                                )
                            }
        }
    }

I would love to know a better way that doesn't involve the inspection route, but this works..

https://stackoverflow.com/questions/25384699/select-all-text-in-a-uitextfield-using-swift/59888336#59888336

Is where I found the solution.

4      

Did you found a solutuion for this?

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.