Reputation: 2281
I am trying to put a TextField in the toolbar of my macOs app. However, the constraints I apply via .frame() do not seem to have any effect. Here is some the test code:
ToolbarTestApp.swift
import SwiftUI
@main
struct toolbartestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.windowStyle(.titleBar)
.windowToolbarStyle(.unified(showsTitle: false))
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
@State var text = ""
var body: some View {
Text("Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!")
.padding()
.toolbar(content: {
ToolbarItem(placement: .principal) {
TextField("example", text: $text)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: .infinity)
}
})
}
}
And here is the result
Can anyone tell me how to make the TextField take up the whole width of the toolbar? And if I have to use a NSViewRepresentable, could you please point me in the right direction?
Thanks
Upvotes: 1
Views: 471
Reputation: 1953
You're not the first to come up with this problem. Apparently, this post also discussed the topic. The way I reproduced your issue and came to a solution is using this content view.
import SwiftUI
struct ContentView: View {
@State var text = ""
var body: some View {
GeometryReader { geo in
Text("Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!")
.padding()
.toolbar(content: {
ToolbarItem(placement: .principal) {
TextField("example", text: $text)
.frame(width: geo.size.width - 20)
.textFieldStyle(.roundedBorder)
}
})
}
}
}
This will give you the screen like this:
As you can see, the text field expands across the entire window.
Upvotes: 1