我正在尝试获取文本并找到匹配的地址,并在表格视图中显示它们-我找到了地址,但是表格视图重新加载了(我正在调用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重新加载并显示所有地址
答案 0 :(得分:0)
您在错误的地方打电话给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
,默认情况下也连接了一个分区。