We’re now almost at the end of our project, but you might have spotted an annoyance: once the keyboard appears for the check amount entry, it never goes away!
This is a problem with the decimal and number keypads, because the regular alphabetic keyboard has a return key on there to dismiss the keyboard. However, with a little extra work we can fix this:
To solve the first one you need to meet your second property wrapper: @FocusState
. This is exactly like a regular @State
property, except it’s specifically designed to handle input focus in our UI.
Add this new property to ContentView
:
@FocusState private var amountIsFocused: Bool
Now we can attach that to our text field, so that when the text field is focused amountIsFocused
is true, otherwise it’s false. Add this modifier to your TextField
:
.focused($amountIsFocused)
That’s the first part of our problem solved: although we can’t see anything different on the screen, SwiftUI is at least silently aware of whether the text field should have focus or not.
The second part of our solution is to add a toolbar button when the text field is active. To make this work really well you need to meet several new SwiftUI views, so I think the best thing to do is show you the code then explain what it does.
Add this new modifier to your form, below the existing navigationTitle()
modifier:
.toolbar {
if amountIsFocused {
Button("Done") {
amountIsFocused = false
}
}
}
Let’s break it down:
toolbar()
modifier lets us specify toolbar items for a view. These toolbar items might appear in various places on the screen – in the navigation bar at the top, in a special toolbar area at the bottom, and so on.amountIsFocused
is currently true, so we only show the button when the text field is active.Button
view we’re using here displays some tappable text, which in our case is “Done”. We also need to provide it with some code to run when the button is pressed, which in our case sets amountIsFocused
to false so that the keyboard is dismissed.You’ll meet these more in the future, but for now I recommend you run the program and try it out – it’s a big improvement!
That was the last step in this project – pat yourself on the back, because we’re finished!
SPONSORED 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! Hurry up because it'll be available only until February 9th.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.