How to add a textfield to toolbar in swiftui (macos)

Viewed 558

I am trying to learn swiftui and faced with "markup" problem. I need to build a UI with textfield in a toolbar (like address line in Safari):

enter image description here

I've tried to do it like this:

import SwiftUI

struct ContentView: View {
    @State var searchText: String = ""
    
    var body: some View {
        NotesListView(notesRepo: InMemoryNotesStubRepository())
            .frame(minWidth: 500, minHeight: 300)
            .toolbar {
                ToolbarItem(placement: .primaryAction){
                    TextField("Search", text: $searchText)
                        .frame(minWidth: 300)
                }
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

And I've got something weird:

enter image description here

Can anyone help me how to add a textfield to a toolbar like in is in Safari (address line)?

1 Answers

It is possible to use style for TextField, like

ToolbarItem(placement: .primaryAction){
    TextField("Search", text: $searchText)
        .textFieldStyle(RoundedBorderTextFieldStyle())
        .frame(minWidth: 300)
}

of even custom style with with look & feel you need, see next for example https://stackoverflow.com/a/63976054/12299030

Related