I have a two text fields on my View. I want to be able to tab between them. It is currently writing the tab into the text content.
struct MyView: View
{
@State var field1: String
@State var field2: String
var body: some View
{
TextEditor(text: $field1)
.disableAutocorrection(false)
.fixedSize(horizontal: false, vertical: true)
.font(Font.system(size: 22, weight: .medium, design: .default))
.multilineTextAlignment(.leading)
.lineLimit(3)
.overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)
TextEditor(text: $field2)
.disableAutocorrection(false)
.fixedSize(horizontal: false, vertical: true)
.font(Font.system(size: 22, weight: .medium, design: .default))
.multilineTextAlignment(.leading)
.lineLimit(3)
.overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 1)
}
}
How do I make the tab jump to the next field? Do I manually need to manage the focus or is there a simpler way?
You can use the
focusable()modifier. Thefocusable()modifier makes a view focusable, which means that it can be selected using the tab key. (This I what makes the tab jump to the next field)Here's an updated version of your code that demonstrates how to make the text fields tabbable:
The two
@FocusStateproperties,isField1FocusedandisField2Focusedrepresent the focus state of each text field, And the focusable modifier is applied to each text field, specifying the corresponding@FocusStateproperty and updating it when the focus is changed..onAppearmodifier is used to setisField1Focusedto true, making the first text field active when the view emerges.If the user presses the Tab key, the focus will automatically move between the text fields, allowing it to switch from one to the other without inserting a tab character into the content.