我正在尝试获取文本并找到匹配的地址并在tableview中显示它们 - 我找到了地址但是tableview dosent reload(我正在调用tableview.reloaddeta())
import UIKit
import MapKit
import Contacts
class LocationSearchTable : UITableViewController{
var searchText:String?
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil
var handleMapSelected:HandleMapSearch? = nil
var locationDelegate : LocationDelegated?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchingItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let selectedItem = matchingItems[indexPath.row].placemark
cell?.textLabel?.text = selectedItem.name ?? "hiiha"
return cell!
}
}
extension LocationSearchTable : LocationDelegated{
func setBar(_ searchText: String?) {
guard let mapView = mapView, let searchBarText = searchText else {return}
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { (response, err) in
guard let response = response else{return}
print(response.mapItems[0].name!)
self.matchingItems = response.mapItems
print(self.matchingItems.count , " this is my size")
*// i see that matchingItems is bigger then 0 but the tableview is allwaze empty*
}
tableView.reloadData()
}
}
我希望tableview重新加载并显示所有地址
你在错误的地方叫reloadData()
。
search.start
异步工作。将线移动到闭合中。
search.start { (response, err) in
guard let response = response else { return }
print(response.mapItems[0].name!)
self.matchingItems = response.mapItems
print(self.matchingItems.count , " this is my size")
self.tableView.reloadData()
}
而这些线路是多余的
tableView.dataSource = self
tableView.delegate = self
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
UITableViewController
默认连接dataSource
和delegate
,默认也有一个部分。