2017-08-26 116 views
1

與子部分的工作,我使用所謂的部分數組變量作爲表視圖具有可摺疊部分:的UISearchBar不是在陣列

var sections = [ 

     // TESTING CODE FOR SECTIONS 
     Section(sec: "One", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

     Section(sec: "Two", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

     Section(sec: "Three", 
       subSec: ["A", "B", "C", "D", "E"], 
       expanded: false), 

我試圖用UISearchController使表視圖搜索。以下是我迄今爲止嘗試,但它不工作:

func filterContentForSearchText(_ searchText: String, scope: String = "All") { 
    filtered = sections.filter({(section : Section) -> Bool in 
    return section.subSec.name.lowercased().contains(searchText.lowercased()) 
    }) 

    tableView.reloadData() 
} 

我瞭解功能的作品,但似乎無法得到它與我的subSec中的變量。

//SEARCH 
    var filteredSections: [String]? 
    let searchController = UISearchController(searchResultsController: nil) 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     //SEARCH 
     filteredSections = sections 
     searchController.searchResultsUpdater = self 
     searchController.hidesNavigationBarDuringPresentation = false 
     searchController.dimsBackgroundDuringPresentation = false 
     tableView.tableHeaderView = searchController.searchBar 

    } 

我收到錯誤,如'不能分配類型'[Section]'的值來鍵入'[String]?'我明白爲什麼,但我不知道如何解決這個問題。

段定義:

struct Section { 
    var sec: String! 
    var subSec: [String]! // [ ] = Array of Strings 
    var expanded: Bool! 

    init(sec: String, subSec: [String], expanded: Bool) { 
     self.sec = sec 
     self.subSec = subSec 
     self.expanded = expanded 
    } 
} 
+0

你究竟想要返回什麼? 'filteredSections'是一個字符串數組,而'sections'是一個'Sections'數組,所以'filteredSections = sections'顯然不起作用。你想返回一個數組或字符串? –

+0

我希望能夠返回subSec的名稱,如果他們匹配搜索字符串。即如果用戶在搜索字段中鍵入'A',則它只會在tableView中顯示'A'。它與一個正常的字符串數組一起工作,但不是我使用sections變量的方式。 – 128K

回答

1

filteredSections是一個字符串數組,你要轉讓叫Section s,這回的Section秒的陣列陣列中的過濾器功能的輸出,所以它顯然是行不通的。

如果你想返回String S作爲過濾的Section在數組的結果,你需要結合filtermap,它可以用一個flatMap來完成。

的flatMap內三元運算符檢查作爲過濾器做了同樣的情況,但如果條件計算結果爲真,nil否則,該flatMap簡單地忽略,因此輸出數組將只包含匹配小節名返回section.subSec.name

func filterContentForSearchText(_ searchText: String, scope: String = "All") { 
    filtered = sections.flatMap{ return $0.subSec.name.lowercased().contains(searchText.lowercased()) ? searchText : nil } 

    tableView.reloadData() 
} 

既然你沒有包括在代碼中的Section定義,我無法測試的功能,但如果subSec.nameString,它會工作得很好。

+0

感謝您的幫助! subSec.name是不可能的,因爲subSec沒有成員'name' – 128K

+0

到你的'tableView'被定義的視圖控制器。 –

+0

Btw哪裏是'subSec.name'來自你的代碼,它沒有在任何地方定義? –