如何正确显示搜索结果?

时间:2015-11-19 08:13:39

标签: ios swift search uisearchdisplaycontroller

我有一个联系人列表tableView与[头像图片 - 名称]。我想在这些用户中搜索。为此,我创建了一个struct [User.swift]:

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

我通过搜索:

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)
    })
}

但它只按字符串部分(名称之间)搜索预期。现在,我如何连接到它联系头像?

我将所有数据保存在数组var users = [User]()中:

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

那么,如何在联系人姓名附近显示图像呢?

2 个答案:

答案 0 :(得分:2)

您应该能够吸引用户

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

然后访问图像

userForRow.image

您可以使用标准单元格来显示图像

cell.imageView.image = userForRow.image

在数据源的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
}

答案 1 :(得分:1)

如果我理解你,你想要显示包含名称和图像的单元格的tableview。那么只需在Interface Builder(或代码,如果需要)中使用标签和imageView创建此单元格,然后在返回表格的单元格时,只需将名称设置为标签的文本,将图像设置为imageView的图像。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell : UserContactCell?

    let userAtIndexPath = filteredUsers[indexPath.row]

    let name = userAtIndexPath.name
    let image = userAtIndexPath.image

    cell = tableView.dequeueReusableCellWithIdentifier("userContactCell") as? UserContactCell

    if(cell == nil)
    {
        tableView.registerNib(UINib(nibName: "UserContactCell", bundle: nil), forCellReuseIdentifier: "userContactCell")

        cell = tableView.dequeueReusableCellWithIdentifier("userContactCell") as? UserContactCell
    }
    }

    cell!.nameLabel.text = name
    cell!.imageView.image = image

    return cell!
}
相关问题