swift - 想在swift中创建一个像google这样的搜索栏
问题描述
我有一个像 ["apple","appear","Azhar","code","BCom"] 等的数组。这个数组包含超过一百万条记录。
现在我想做的是UISearchBar
在谷歌中放置一个like,然后每当用户输入文本时,下拉列表就会出现包含该文本的所有结果,用户可以从列表中选择一个。
例如 - 如果用户键入“a”,那么“apple”、“appear”和“Azhar”将出现在下拉列表中。
我不想使用 aUITableView
或其他任何东西来加载记录。每当用户键入任何单词时,它都应该从数组中收集记录并进行下拉以显示它们。
我怎样才能做到这一点?需要的建议请。
解决方案
非常简单的代码可以解决问题,搜索栏过滤器很简单,至于下拉菜单,我使用了一个名为“DropDown”的第三方 Pod,非常易于使用:https ://github.com/AssistoLab/DropDown
import UIKit
import DropDown
class ViewController: UIViewController, UISearchBarDelegate {
var data: [String] = ["apple","appear","Azhar","code","BCom"]
var dataFiltered: [String] = []
var dropButton = DropDown()
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
dataFiltered = data
dropButton.anchorView = searchBar
dropButton.bottomOffset = CGPoint(x: 0, y:(dropButton.anchorView?.plainView.bounds.height)!)
dropButton.backgroundColor = .white
dropButton.direction = .bottom
dropButton.selectionAction = { [unowned self] (index: Int, item: String) in
print("Selected item: \(item) at index: \(index)") //Selected item: code at index: 0
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
dataFiltered = searchText.isEmpty ? data : data.filter({ (dat) -> Bool in
dat.range(of: searchText, options: .caseInsensitive) != nil
})
dropButton.dataSource = dataFiltered
dropButton.show()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
for ob: UIView in ((searchBar.subviews[0] )).subviews {
if let z = ob as? UIButton {
let btn: UIButton = z
btn.setTitleColor(UIColor.white, for: .normal)
}
}
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
dataFiltered = data
dropButton.hide()
}
}
推荐阅读
- python - 使用 h5py 在 HDF5 文件中自定义列名
- javascript - 如何从所有 php 文本 id 中获取元素?
- mapbox - Mapbox GL JS querySourceFeatures到矢量瓦片层
- angular - Angular 如何从配方错误中删除照片无法读取未定义的属性“拼接”
- python - Pandas - 获取一些没有指定的上一行/下一行的值
- android-studio - Android Studio org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败:
- linux - 无法在小学中打开两个终端窗口
- javascript - 关闭画布菜单 - onclick 功能问题
- c# - 当 API 出现问题时返回错误消息
- python - 将notepad.txt中的内容导入table.xlsx