无法设置搜索栏Swift 4

时间:2018-06-30 13:23:30

标签: ios swift

我需要设置一个包含一组位置的部分的表视图。 我设法做到了所有这些,但现在我受困于搜索栏,该栏可以帮助用户在知道名称的情况下查找某些位置。

这是我的代码:

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
    }

这是我遇到的问题。会在搜索栏中接受文本并根据该文本过滤数据的人:

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

我得到了错误:

  

“ [PlacesList.LocationsStruct]”类型的值没有成员“名称”

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您的问题是您有一个嵌套数组,因此location不是对象而是数组,因此您可以尝试

filteredData = twoDiemArray.filter { (locations) -> Bool in

       return locations.filter { (location) -> Bool in
            return location.name.lowercased().contains(searchText.lowercased())
     }.count != 0

}