I need to setup a tableview with sections of a set of locations. I managed to do all of it but now I'm stuck with the searchbar that helps the user to find certain locations if they know the name.
Here is my code:
class PlacesList: UITableViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
struct LocationsStruct {
let name: String
let lat: CLLocationDegrees
let long: CLLocationDegrees
let image: UIImage
let description: String
}
let cellId = "cellId"
let twoDiemArray = [
[LocationsStruct(name: "Jolie Golf ", lat: 27.949315, long: 34.363702, image: #imageLiteral(resourceName: "hotelIcon"), description: "sessions are held here"),
LocationsStruct(name: "Club Reef Hotel", lat: 27.887805, long: 34.324911, image: #imageLiteral(resourceName: "hotelIcon"), description: "hello"),
LocationsStruct(name: "Dreams Beach Resort", lat: 27.875648, long: 34.317508, image: #imageLiteral(resourceName: "hotelIcon"), description: "hello"),
LocationsStruct(name: "Ras Mohamed Nature Reserve", lat: 27.747882, long: 34.235658, image: #imageLiteral(resourceName: "hotelIcon"), description: "hello")
],
[LocationsStruct(name: "Jolie Restaurant ", lat: 27.949315, long: 34.363702, image: #imageLiteral(resourceName: "hotelIcon"), description: "you can eat here"),
LocationsStruct(name: "Club ", lat: 27.887805, long: 34.324911, image: #imageLiteral(resourceName: "hotelIcon"), description: "you can dance here"),
LocationsStruct(name: " Beach", lat: 27.875648, long: 34.317508, image: #imageLiteral(resourceName: "hotelIcon"), description: "you can swim here")]
]
var filteredData = [
[LocationsStruct]
]()
override func viewDidLoad() {
super.viewDidLoad()
filteredData = twoDiemArray
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
searchBar.delegate = self
}
And this is the function where I'm stuck. The one that accepts text in search bar and filters data based on that text:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = twoDiemArray.filter({( location : LocationsStruct) -> Bool in
return location.name.lowercased().contains(searchText.lowercased())
})
if searchText == "" {
filteredData = twoDiemArray
}
tableView.reloadData()
}
I get the error:
Value of type '[PlacesList.LocationsStruct]' has no member 'name'
How can I fix that?
Your problem is that you have a nested array so location is not an object it's an array , so you can try
filteredData = twoDiemArray.filter { (locations) -> Bool in
return locations.filter { (location) -> Bool in
return location.name.lowercased().contains(searchText.lowercased())
}.count != 0
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.