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

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.

1      

@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.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.