簡體   English   中英

如何使用搜索欄搜索多個視圖? (iOS Swift)

[英]How to use the Search Bar to search through Multiple Views? (iOS Swift)

iOS,Swift

該應用程序現在做了什么:

此應用程序的主視圖包含類別(排列在表格視圖中),當單擊這些類別時,應用程序將用戶帶到具有基本文本和圖像的滾動視圖。 主視圖還包含一個搜索欄。 用戶可以輸入類別名稱,並過濾結果。

應用程序需要做什么:

我想更好地搜索欄,並過濾結果。 我希望用戶能夠過濾類別名稱,不僅可以輸入類別名稱,還可以輸入特定滾動視圖中包含的文本。

例如:類別名稱為:“字母”和“數字”。 當用戶點擊“信件”時,它們被帶到一個顯示“ABCD .. Z”的視圖,當點擊“數字”時,它們被帶到顯示“1 2 3 4 ... 10”的視圖。 如果用戶在搜索欄中輸入“AB”,則主視圖會過濾以僅顯示“信件”類別。 如果用戶在搜索欄中輸入“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
}

如果需要,將顯示更多代碼。

這里有一些問題:

  • 你的數據是如何構建的?

作為解決方案,我會這樣做:

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中都不會找到“AB”。 如果搜索是“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變量
    • 繼續下一個字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM