[英]SwiftUI - How to put TextField in navigation bar like settings app
In the native Settings app, there's a NavigationView
with a TextField
inside of it that nicely transitions as the user scrolls:在本机设置应用程序中,有一个带有
TextField
的NavigationView
,它可以随着用户滚动而很好地转换:
I was able to create something similar using:我能够使用以下方法创建类似的东西:
struct HomeView: View {
@State var searchQuery: String = ""
var body: some View {
NavigationView {
List {
TextField("Search", text: $searchQuery).textFieldStyle(RoundedBorderTextFieldStyle())
}
.navigationBarTitle(Text("My App"))
}
}
}
which gave me this:这给了我这个:
However, this doesn't really look or act the same as the native settings one, and I'm lost on how to even get the search icon in there.但是,这看起来或行为与本机设置不同,我什至不知道如何在其中获取搜索图标。 Thanks so much!
非常感谢!
What youre trying to create in SwiftUI would be a UISearchBar in swift's UIKit.您要在 SwiftUI 中创建的内容将是 swift 的 UIKit 中的 UISearchBar。
So you need to stylize the textfield所以你需要对文本字段进行风格化
TextField("Search ...", text: $text)
.padding(7)
.padding(.horizontal, 25)
.background(Color(.systemGray6))
.cornerRadius(8)
.padding(.horizontal, 10)
.onTapGesture {
self.isEditing = true
}
And in order to achieve the magnifying glass icon which is standard for a UISearchBar item.并且为了实现 UISearchBar 项的标准放大镜图标。 We need to add them manually with an overlay in SwiftUI
我们需要在 SwiftUI 中手动添加它们
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)
if isEditing {
Button(action: {
self.text = ""
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
) )
you can reference this article for more https://www.appcoda.com/swiftui-search-bar/您可以参考这篇文章了解更多https://www.appcoda.com/swiftui-search-bar/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.