У меня проблема с моей панелью поиска. Я хотел бы отобразить название места в зависимости от того, какой тип в строке поиска
JSON file
"places": [
{
"name": "Acacias",
"type": "accommodations",
"latitude": 48.766149,
"longitude": 2.273054,
"pictures": ["Acacias.jpg"]
},
{
"name": "Accueil",
"type": "departments",
"latitude": 48.766621,
"longitude": 2.278807,
"pictures": ["Entree.jpg"],
"phone": "+33 1 41 87 20 30"
},
{
"name": "Auditorium",
"type": "rooms,installations",
"latitude": 48.765548,
"longitude": 2.274028,
"pictures": ["Auditorium.jpg"],
"surface": 175,
"equipments": ["Video", "Sono"],
"capacity": 115
},
{
"name": "Bain froid",
"type": "installations",
"latitude": 48.764497,
"longitude": 2.272886,
"pictures": ["Bain-froid.jpg"]
},
{
"name": "Beach-Volley",
"type": "installations",
"latitude": 48.765979,
"longitude": 2.276327,
"pictures": [],
"surface": 520,
"capacity": 20
},
{
"name": "Cèdres",
"type": "accommodations",
"latitude": 48.766594,
"longitude": 2.273457,
"pictures": ["Cedres.jpg"]
},
{
"name": "C4",
"type": "rooms",
"latitude": 48.766248,
"longitude": 2.274697,
"pictures": ["ClubHouse1.jpg"],
"surface": 25,
"equipments": ["Video", "Sono"],
"capacity": 12
},
Я получаю данные Grace DataManager file
import Foundation
struct Place: Decodable {
var name: String
var type: String
var latitude: Double
var longitude: Double
var pictures: [String]?
var surface: Int?
var equipments: [String]?
var capacity: Int?
var description: String?
var phone: String?
var opening: String?
}
struct AppResponseData: Decodable {
var places: [Place]
}
class DataManager {
var places: [Place]?
/**
Accès à l'instance de la classe
*/
static let shared = DataManager()
/**
Constructeur privé pour n'avoir qu'un singleton
*/
private init() {
loadJSON()
}
/**
Charge les données du fichier JSON
*/
private func loadJSON(){
if let filepath = Bundle.main.url(forResource: "places", withExtension: "json") {
do {
let fileData = try Data(contentsOf: filepath)
let jsonDecoder = JSONDecoder()
let jsonData = try jsonDecoder.decode(AppResponseData.self, from: fileData)
self.places = jsonData.places
} catch {
print("error:\(error)")
}
}
}
/**
Obtenir une liste d'éléments filtrés par type
- filter : Filtre de sélection
*/
func getFiltered(filter: String) -> [Place] {
var filteredPlaces: [Place] = []
if let places = self.places {
for place in places {
if place.type.contains(filter) {
filteredPlaces.append(place)
}
}
}
return filteredPlaces
}
}
Я хочу вставить панель поиска, чтобы классифицировать мои данные по имени.
Мой файл TableViewController
import UIKit
/**
Affichage du tableau par filtre "type"
*/
class ListePlaces: UITableViewController, UISearchBarDelegate {
var filter: String = ""
var selectedPlace = 0
var listData: [Place]?
var filterListeData = [Place]()
@IBOutlet var table: UITableView!
@IBOutlet weak var searchBarPlace: UISearchBar!
/***
Affichage des places par le tableau
*/
override func viewDidLoad() {
self.listData = DataManager.shared.getFiltered(filter: filter)
setUpSearchBar()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if let places = listData {
return places.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "placeCell", for: indexPath)
_ = UITableView()
cell.backgroundColor = UIColor.white
cell.textLabel?.textColor = UIColor.black
if let places = listData {
cell.textLabel?.text = places[indexPath.row].name
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedPlace = indexPath.row
performSegue(withIdentifier: "showPlace", sender: self)
}
/***
Récupérer les informations pour chaque place et les renvoyer sur une autre page en les récupérant avec place
Grace au selectedPlace
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let places = listData {
let place = places[self.selectedPlace]
guard let resultPlace = segue.destination as? ResultPlace else {
fatalError("Problème avec le choix d'un lieu")
}
resultPlace.place = place
}
}
private func setUpSearchBar(){
searchBarPlace.delegate = self
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("aaa")
filterListeData = (listData?.filter({ Place -> Bool in
// print("bbbb")
guard let text = searchBarPlace.text else {return false}
// print("cccc")
return Place.name.contains(text)
}))!
table.reloadData()
// print("eeee")
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
}
}
Но функция панели поиска не работает.