Search code examples
swiftswiftuiautocompletetoolbar

making .toolbar to add text to Textfield in SwiftUI


I have the following code in swiftUI.

private var emailSection: some View {
        Section {
            HStack {
                UVFloatingTextField(title: "E-Mail", text: $email, keyboardType: .emailAddress)
                    .toolbar {
                        ToolbarItemGroup(placement: .keyboard) {
                            Button("@gmail.com") {
                                print("Clicked")
                            }
                            
                            Spacer()
                            
                            Button("Done") {
                                isInputActive = false
                            }
                        }
                    }

                if email.isEmpty {
                    MandatoryInfo()
                }
            }
        } header: {
            Text("Angaben zur E-Mail")
                .sectionHeader()
        }
    }

and the output looks like this. Which is my TextField

Screenshot

I would like to add more buttons like @gmail.com and when user clicks the button it will complete the input in textfield.

For example, user types "user123" in textfield and instead of manually writing @gmail.com clicks "@gmail.com" which writes it in the text field. If there is a better way then using Button or taskbar I am also open for suggestions. Thank you!

I have expected to make button work as my own autocomplete tool, but i couldn't figure out how to make it.


Solution

  • I haven't tested this but I'm pretty sure this should work

    Button("@gmail.com") {
        print("Clicked")
        self.email += "@gmail.com"
    }