所以我的问题是我想在 FirstSearch.swift 列表中搜索名称,但我也想在搜索结果中显示图像和城镇。我不知道该怎么做,而且我对 Swift 编程有点陌生。所以有人可以帮我写代码吗
我的 FirstSearch.swift
import Foundation
class People {
class Input {
let imageName: String
let userName: String
let userTown: String
init(iName: String, uName: String, uTown: String){
self.imageName = iName
self.userName = uName
self.userTown = uTown
}
}
let peopleList = [
Input(iName: "Habib.jpg", uName: "Habib Badiane", uTown: "Emden, Deutschland"),
Input(iName: "John.jpg", uName: "John Adams", uTown: "Emden, Deutschland"),
Input(iName: "Marcus.jpg", uName: "Marcus Dirks", uTown: "Emden, Deutschland"),
Input(iName: "0.jpg", uName: "Tobias Tebben", uTown: "Emden, Deutschland"),
Input(iName: "Neda.jpg", uName: "Neda Heidari", uTown: "Emden, Deutschland"),
Input(iName: "Gudrun.jpg", uName: "Gudrun Burlefinger", uTown: "Emden, Deutschland")
]
}
我的 FirstSearchTableViewController.swift
import UIKit
class FirstSearchTableViewController: UITableViewController, UISearchResultsUpdating {
let people = People()
var filteredTableData = [String]()
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
// Reload the table
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active) {
return self.filteredTableData.count
}
else {
return people.peopleList.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! FirstSearchTableViewCell
let input = people.peopleList[indexPath.row]
let image = UIImage(named: input.imageName)
cell.profileImg.image = image
cell.profileName.text = input.userName
cell.profileCity.text = input.userTown
// Configure the cell...
if (self.resultSearchController.active) {
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.textLabel?.text = people.peopleList[indexPath.row]
return cell
}
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
let array = (people.peopleList as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
}