NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

prevent duplicate toolbar buttons

Forums > SwiftUI

I have a custom view named MyTextField that creates a TextField and places a button in the keyboard toolbar that dismisses the keyboard. If I have a screen that creates three instances of MyTextField, I get three buttons in the keyboard toolbar that all dismiss the keyboard. How can I prevent adding three buttons that do that same thing? I don't see a way that I can determine whether the button is already in the keyboard toolbar so I can avoid adding another one.


@mark might be mixing logic and language?

I don't see a way that I can determine whether the button is already in the keyboard toolbar so I can avoid adding another one.

SwiftUI is a declarative language. You tell SwiftUI what you want on the screen. You've not provided any clues via code snips. (Why?!?) So this is all guesswork.

I am guessing that SwiftUI is doing exactly what you're telling it to do.

  1. I have a MyTextField that adds one button to the keyboard toolbar.
  2. When I add MyTextField to the view, then add that button per step 1.
  3. When I add THREE MyTextFields, then naturally add THREE buttons to the keyboard toolbar.

Somewhere in @twoStraws lessons, he talks about focused functionality. Design a view to do one thing, and do it well.

Without seeing your code, it seems you have MyTextField doing more than one thing. Consider refactoring MyTextField. Move the code that adds a keyboard toolbar button into a smaller more focused func.

  1. Layout the form.
  2. Add MyTextField #1
  3. Add MyTextField #2
  4. Add MyTextField #3
  5. (new func) Add dismiss button to keyboard.

Another technique might be to have an @State variable named showDismissButton in your view struct. If MyTextField has focus, toggle showDismissButton to true. Then wire up the button to hide if showDismissButton is false.

These are just rapid, random ideas.


Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.