Search code examples
iosswiftsearchuisearchdisplaycontroller

How to correctly show search results?


I have a contact list tableView with the [Avatar Image - Name]. And I want to search among this users. For this I created a struct [User.swift]:

struct User {
    let name : String
    let image: UIImage
}

And I search via:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    self.filteredUsers = self.users.filter({( user : User) -> Bool in
        let stringMatch = user.name.rangeOfString(searchText)
        return (stringMatch != nil)
    })
}

but it searches just by String part(among names) as expected. Now, how can I connect to it contact avatar images?

I save all in an array var users = [User]() as:

self.users.append(User(name: user.displayName, image: UIImage(data: photoData!)!))

So, how can I show images too near the contact name?


Solution

  • You should be able to get your user

    let userForRow:User = self.filteredUsers[indexPath.row]
    

    then access the image

    userForRow.image
    

    you can use a standard cell to display the image

    cell.imageView.image = userForRow.image
    

    in the datasource's cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let user = filteredUsers[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath indexPath)
    
        cell.textLabel.text = user.name
        cell.imageView.image = user.image
    
        return cell
    }