swift - 自动完成搜索栏 - 不是值单元格

标签 swift autocomplete uisearchbar

我正在尝试实现一个具有自动完成功能的搜索栏。我希望当我开始输入后没有值时,会出现一个单元格“无结果”。但是当我第一次选择 searchField 或删除其中的所有字符时,单元格就会消失。我设法让它在 searchField 为“”时出现,但我找不到一种方法让它像我描述的那样工作。

我的代码:

@IBOutlet weak var searchField: UISearchBar!
@IBOutlet var autocompleteTableView: UITableView!

var pastUrls = ["Men", "Women", "Cats", "Dogs", "Children"]
var autocompleteUrls = [String]()
var searchActive : Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    searchField.delegate = self
    autocompleteTableView.backgroundColor = UIColor.clearColor()
    autocompleteTableView!.delegate = self
    autocompleteTableView!.dataSource = self
    autocompleteTableView!.scrollEnabled = true
    autocompleteTableView!.hidden = true
}


func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    autocompleteTableView.hidden = false
    let substring = (searchBar.text! as NSString).stringByReplacingCharactersInRange(range, withString: text)
    searchAutocompleteEntriesWithSubstring(substring)
    return true
}

func searchAutocompleteEntriesWithSubstring(substring: String) {
    autocompleteUrls.removeAll(keepCapacity: false)
    for curString in pastUrls {
        if curString.lowercaseString.rangeOfString(substring) != nil {
            autocompleteUrls.append(curString)
        }
    }
    autocompleteTableView!.reloadData()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return autocompleteUrls.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell")

    if let _ = cell {
        let index = indexPath.row as Int
        cell!.textLabel!.text = autocompleteUrls[index]
    } else {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cell")
    }
    return cell!

}

最佳答案

您需要检查您的 numberOfRowsInSection 方法,您的数组是否为空以及是否返回 1。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if autocompleteUrls.count != 0 {
        return autocompleteUrls.count
    }

    return 1

}

此外,您可以使用 GitHub 中的 DZNEmptyDataSet这是一组很好的委托(delegate)方法,如果没有要显示的数据,它将在您的 tableView 中显示一些内容。

关于swift - 自动完成搜索栏 - 不是值单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134303/

相关文章:

jquery - 未捕获的 TypeError : $(. ..).autocomplete 不是函数

jquery - 将 jQuery 自动完成项呈现为内联 block

ios - 使用 UIBarButtonItem 将 UISearchBar 添加到 UINavigationBar

ios - 方向更改时以编程方式更改 UISearchBar 的框架

ios - 如何打开带有所选单元格标题的导航 Controller

ios - Swift - 两个具有相同公共(public)结构的框架

c# - 覆盖或重载自动完成追加规则

swift - 如何在文件打开时收到通知

ios - Swift PDFKit 分页无法正常工作

ios - 调整导航栏中 UISearchBar 的大小?