Rav*_*ati 6 country-codes searchbar swift swiftui swiftui-list
我点击选择器,它将打开屏幕,屏幕上显示元素列表,我们可以添加搜索栏吗?
我实现了国家/地区选择器,在国家/地区列表中显示国家/地区名称和国家/地区代码,以便在该列表屏幕上添加搜索栏轻松查找国家/地区。
struct ContentView: View {
//All Country get from the plist with country Code and Coutnry Name.
let countyList = Country().getAllCountyInfo()
// Selected Country
@State private var selectedCountry = 0
var body: some View {
NavigationView {
Form {
Picker(selection: $selectedCountry, label: Text("Country")) {
ForEach(countyList) { country in
HStack{
Text(country.countryName ?? "")
Spacer()
Text(country.countryCode ?? "")
}
}
}
}
.navigationBarTitle("Select country picker")
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过运行上面的代码,它将打开一个像上面屏幕一样的国家/地区列表。
在上面的屏幕上(国家/地区列表)。
如何添加搜索栏来过滤国家/地区数据?
您可以添加一个TextField充当选择器主体中的搜索栏:
搜索条形码:
struct SearchBar: View {
@Binding var text: String
@State var isEditing = false
var body: some View {
HStack {
TextField("Search Countries", text: $text)
.padding(7)
.padding(.horizontal, 25)
.background(Color.gray)
.cornerRadius(8)
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.gray)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)
if isEditing {
Button(action: {
text = ""
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
).padding(.horizontal, 10)
.onTapGesture {
isEditing = true
}
if isEditing {
Button(action: {
UIApplication.shared.endEditing(true)
isEditing = false
text = ""
}) {
Text("Cancel")
}.padding(.trailing, 10)
.transition(.move(edge: .trailing))
.animation(.default)
}
}
}
}
extension UIApplication {
func endEditing(_ force: Bool) {
self.windows
.filter{$0.isKeyWindow}
.first?
.endEditing(force)
}
}
extension View {
func resignKeyboardOnDragGesture() -> some View {
gesture(
DragGesture()
.onChanged { _ in
UIApplication.shared.endEditing(true)
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
带搜索栏的选择器:
struct ContentView: View {
@State var data: [String] = //your data
@State var searchText = ""
@State var selection: String?
var displayedData: [String] {
return data.filter({searchText.isEmpty ? true: $0.lowercased().contains(searchText.lowercased())})
}
var body: some View {
Picker("Title", selection: $selection) {
SearchBar(text: $searchText)
ForEach(displayedData, id: \.self) { item in
Text(item)
.tag(item)
}.resignKeyboardOnDragGesture()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6478 次 |
| 最近记录: |