swift - 想快速创建一个像谷歌这样的搜索栏

标签 swift xcode uisearchbar searchbar

我有一个数组,如 ["apple","appear","Azhar","code","BCom"] 等。这个数组包含超过 50 万条记录。

现在我想做的是像在 google 中那样放置一个 UISearchBar 然后每当用户键入文本时,下拉列表就会出现包含该文本的所有结果,用户可以选择列表中的一个。

例如 - 如果用户键入“a”,则“apple”、“appear”和“Azhar”将出现在下拉列表中。

我不想使用 UITableView 或其他任何东西来加载记录。每当用户键入任何单词时,它都应该从数组中收集记录并下拉以显示它们。

我该怎么做? 请提出建议。

最佳答案

非常简单的代码就可以解决这个问题,搜索栏过滤器很简单,至于下拉菜单,我使用了一个名为“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()
}
}

enter image description here

关于swift - 想快速创建一个像谷歌这样的搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51789511/

相关文章:

ios - 使 UIImageView 适合屏幕宽度但保持宽高比 [swift]

javascript - 在 Safari App Extension 中以编程方式加载弹出窗口

ios - tapGesture 超链接 swift

ios - 如何在循环中执行多个 guard 语句?

ios - 动态大小的 TableView 创建 AutoLayout 问题

swift - swift 中的 “This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread”

iphone - 适用于 iOS 5 和 iOS 6 的 Facebook 集成

ios - UISearchController 就像 Instagram Explore Tab

ios - 选择时 UISearchController 崩溃

ios - 如何隐藏分段控件?