Search Bar in Table View Swift

2019-09-18 02:35发布

问题:

im doing a simple project in Xcode 6 and i want to add search bar in tableviewcontroller but something is not working for me. Im doing it by this tutorial http://www.raywenderlich.com/76519/add-table-view-search-swift

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        return self.filteredProgramy.count
    } else {
        return self.programy.count
    }
}

here im getting error "fatal error: unexpectedly found nil while unwrapping an Optional value". idk why. whole code is here

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        return self.filteredProgramy.count
    } else {
        return self.programy.count
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    var program : Program

    if tableView == self.searchDisplayController!.searchResultsTableView {
        program = filteredProgramy[indexPath.row]
    } else {
        program = programy[indexPath.row]
    }


func filterContentForSearchText(searchText: String) {
    // Filter the array using the filter method
    var scope = String()
    self.filteredProgramy = self.programy.filter({( program: Program) -> Bool in
        let categoryMatch = (scope == "All") || (program.category == scope)
        let stringMatch = program.name.rangeOfString(searchText)
        return categoryMatch && (stringMatch != nil)
    })
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString)
    return true
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
    self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
    return true
}

}

回答1:

self.searchDisplayController is nil.

I just downloaded the tutorial's sample code (which you should do as well) and I see that the author has a "Search Display Controller" in their nib file. Check your nib file and be sure that the Candy Search controller is hooked up properly.

It's supposed to look like this:

To get to that image right click on the Search Display Controller object in the .xib file. Notice in my image that "Referencing Outlets" has a connection between searchDisplayController and CandySearch. That's what you are missing.

To create the connection ctrl drag from the CandySearch controller to the `Search Display Controller" when you let go of the mouse you will see:

Click searchDisplayController and you should be good to go.

Lastly, you should read up on how optionals work in Swift to help you understand issues like this in the future:

https://developer.apple.com/librarY/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456



回答2:

I had a similar issue and found the following to work. The 'cell' variable in your code is nil because while you have set the number of rows, the actual cell object has not yet been created (line cell = UITableView(.. below)

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell : UITableViewCell
    var player : Player

    if self.searchDisplayController!.active {
        var searchCell: AnyObject? = self.tableView.dequeueReusableCellWithIdentifier("Cell")

        if searchCell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        } else {
            cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
        }            

        player = self.filteredPlayers[indexPath.row]
    } else {
        cell = self.tableView.dequeueReusableCellWithIdentifier(TableCellNamesEnum.PLAYER_DETAIL_CELL.rawValue, forIndexPath: indexPath) as UITableViewCell
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        player = self.selectedPlayers[indexPath.row]
    }

    cell.textLabel!.text = "\(player.firstName) \(player.lastName)"

    return cell
}