SwiftUI Xcode 12中macOS应用程序工具栏中的搜索栏

4
在最新版本的Xcode(12)中,默认情况下,在应用程序顶部现在有一个工具栏。
我喜欢这个设计,但我还不太明白如何使用它。它似乎与普通视图的工作方式不同。 enter image description here 现在,我想将搜索栏添加到其中,使其在自适应布局中尽可能覆盖所有空间。但这似乎行不通。至少不像在普通的View中那样。(我必须补充说明,当涉及SwiftUI时,我还不是很有经验)。
这就是我的搜索栏现在的样子(紧挨着Button右侧的微小蓝色东西,只有在我输入时才会扩展):
这是我的主View中工具栏的相应代码:
var body: some View {
        List {
            ForEach(items) { item in
                if !installedOnly || item.installed {
                    Text("\(item.name!)")
                        .foregroundColor(item.installed && !installedOnly ? .green : .white)
                }
            }
            .onDelete(perform: deleteItems)
        }
        .toolbar {
            HStack{
                TextField("", text: $search_term)
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                Button(action: togglePinned) {
                    Label("Add Item", systemImage: installedOnly ? "pin.fill" : "pin")
                }
                Button(action: getApps) {
                    Label("Add Item", systemImage: "arrow.clockwise")
                }
            }
        }
    }

任何反馈都非常感谢!

1
我也无法让它工作。无论在.frame()中放入什么,TextField都不会拉伸或收缩。 - jfoucher
1个回答

1
不要使用HStack来制作工具栏内容,工具栏中的每个视图都是一个项目。
.toolbar {
     TextField("", text: $search_term)
         .textFieldStyle(RoundedBorderTextFieldStyle())
         .frame(minWidth: 200)
     Button(action: togglePinned) {
         Label("Add Item", systemImage: installedOnly ? "pin.fill" : "pin")
     }
     Button(action: getApps) {
         Label("Add Item", systemImage: "arrow.clockwise")
     }
}

你知道这对于菜单栏应用程序如何工作吗?我尝试了这段代码,但它无法在菜单栏基础设施中呈现搜索栏。 - Mansidak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接