如何使用搜索栏搜索多个视图? (iOS Swift)

时间:2017-03-21 20:17:42

标签: ios swift xcode searchbar

iOS,Swift

应用程序现在做了什么:

此应用程序的主视图包含类别(排列在表格视图中),当单击这些类别时,应用程序会将用户带到包含基本文本和图像的滚动视图。主视图还包含一个搜索栏。用户可以输入类别名称,并过滤结果。

应用程序需要做什么:

我想更好地搜索栏,并过滤结果。我希望用户能够过滤类别名称,不仅可以输入类别名称,还可以输入特定滚动视图中包含的文本。

例如:类别名称为:"字母"和"数字"。当用户点击" Letters"时,他们会被带到一个视图,说明" A B C D .. Z",当"数字"单击后,它们会显示在" 1 2 3 4 .. 10"中。如果用户输入" A B"在搜索栏中,主视图过滤器仅显示"字母"类别。如果用户输入" 3"在搜索栏中,主视图过滤器仅显示"数字"类别。

结论:

我还是应用程序开发的新手,这让我很难过。无论是代码还是参考,都会非常感谢任何帮助。

谢谢。

TableViewController

变量:

@IBOutlet var searchForTool: UISearchBar!
@IBOutlet var toolTable: UITableView!

var searchActive : Bool = false
var filtered : [String] = []
var data = ["  Make", "  Model"]
var identities = ["A", "B"]

搜索栏过滤器:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = data.filter({ (text: String) -> Bool in

        return text.range(of: searchText, options: String.CompareOptions.caseInsensitive) != nil
    })

    if(filtered.count == 0){
        searchActive = false
    } else {
        searchActive = true
    }
    self.toolTable.reloadData()
}

显示的单元格:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell

    if(searchActive){
        cell.toolLabel.text = filtered[indexPath.row]
    } else {
        cell.toolLabel.text = data[indexPath.row]
    }
    return cell
}

如果需要,将显示更多代码。

1 个答案:

答案 0 :(得分:0)

这里有一些问题:

  • 您的数据结构如何?

作为解决方案,我会选择这样的事情:

class Item {
    var name: String!
    init(name: String) {
        self.name = name
    }
}

class Category {
    var items = [Item]()
    var name: String!

    init(items: [Item], name: String) {
        self.items = items
        self.name = name
    }
}

你可以像这样使用它:

let letterItems = [Item(name: "A"), Item(name: "B"), Item(name: "C")]
let lettersCategory = Category(items: letterItems, name: "Letters")

let numberItems = [Item(name: "1"), Item(name: "2"), Item(name: "3")]
let numbersCategory = Category(items: numberItems, name: "Numbers")

let cat: [Category] = [lettersCategory, numbersCategory]
  • 您的搜索定义如何?

您可以在这里有多个选项:

  1. 需要找到搜索文本,因为它是用category.name或item.name中的任何一个编写的:在这种情况下,在任何item.name中都找不到“A B”。如果搜索是“A” - > “信件”是匹配

    let searchItem = "A"
    
    let result = cat.filter({ $0.name.range(of: searchItem) != nil || $0.items.filter({$0.name.range(of: searchItem) != nil }).count > 0})
    
  2. 一个“或”搜索,就像谷歌一样:

    • 首先用“”
    • 分隔搜索字符串
    • 获取每个元素并使用与上面相同的方法 -
    • 展平结果
    • 添加到results变量
    • 继续下一个字