gpt4 book ai didi

swift - SearchController 不显示程序化的 collectionView 单元格

转载 作者:行者123 更新时间:2023-11-30 12:02:53 24 4
gpt4 key购买 nike

我正在尝试实现一个搜索 Controller 。从数组显示一切正常。现在我试图显示 MapKit 的结果,但在 collectionView 中看不到任何内容。我正在以编程方式完成所有操作,因此这可能就是我将 collectionView 调用为 resultsView 的方式。我做错了什么?

这是主视图 Controller : 导入 UIKit 导入MapKit

class LocationVC: UIViewController, MKMapViewDelegate {

let locationManager = CLLocationManager()
var resultSearchController:UISearchController? = nil

let mapView : MKMapView = {
let map = MKMapView()
map.translatesAutoresizingMaskIntoConstraints = false
return map
}()

override func viewDidLoad() {
super.viewDidLoad()

let window = UIWindow.init(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()

setupBasicNavigation(title: "")
setupLocationManager()
setupMapView()

mapView.delegate = self
mapView.showsUserLocation = true

navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelAndGoBack))

setupSearchController()
searchBarSetup()


}

//MARK: Setting up the Search Bar
func searchBarSetup() {
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
navigationItem.titleView = resultSearchController?.searchBar

resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
}

//MARK: Setting up the Search Controller
func setupSearchController() {
let locationSearchTable = LocationSearchTable()
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable as UISearchResultsUpdating
locationSearchTable.modalPresentationStyle = .currentContext
self.present(locationSearchTable, animated: false, completion: nil)
locationSearchTable.mapView = mapView
//self.present(locationSearchTable, animated: false, completion: nil)
}

//MARK: Setting up the Map View
func setupMapView() {
view.addSubview(mapView)
mapView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
mapView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
mapView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
mapView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
}

//MARK: Setting up the Location Manager
func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}

//MARK: Sends to the back controller
func cancelAndGoBack() {
print("Canceled and Saved")
self.dismiss(animated: true, completion: nil)
}


}

//MARK: Extension to provide the delegates methods for LOcation
extension LocationVC : CLLocationManagerDelegate {
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: \(error)")
}
}

这是结果的 View Controller :

    import UIKit
import MapKit

class LocationSearchTable: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

var collectionView: UICollectionView!

var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil

override func viewDidLoad() {
super.viewDidLoad()

let window = UIWindow.init(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()

setupCollectionView()
setupBasicNavigation(title: "")


}

//MARK: Setup CollectionView
func setupCollectionView() {

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 50, left: 0, bottom: 110, right: 0)
layout.itemSize = CGSize(width: view.frame.size.width, height: 40)

layout.minimumLineSpacing = 1

collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self as UICollectionViewDataSource
collectionView.delegate = self

//collection view design
collectionView?.backgroundColor = UIColor(r: 242, g: 240, b: 240)
collectionView?.alwaysBounceVertical = false
collectionView?.showsVerticalScrollIndicator = false
collectionView?.scrollsToTop = false

collectionView.register(LocationCell.self, forCellWithReuseIdentifier: "LocationCell")

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return matchingItems.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LocationCell", for: indexPath) as! LocationCell
cell.contentView.backgroundColor = .white
cell.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor
cell.layer.borderWidth = 0.3

let selectedItem = matchingItems[indexPath.row].placemark
cell.itemName.text = selectedItem.name

return cell
}

//cell function to determine size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

return CGSize(width: view.frame.width, height: 40)
}

}

//MARK: Extension for Search Controller Delegate
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {

}
func updateSearchResultsForSearchController(searchController: UISearchController) {
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response else {
return
}
self.matchingItems = response.mapItems
self.collectionView.reloadData()
}
}
}

最佳答案

看来我正在使用:

func updateSearchResultsForSearchController

当我应该使用时:

func updateSearchResults(for searchController: UISearchController) {

将代码从 updateSearchResultsForSearchController 复制到 updateSearchResults 就成功了,因为这是我使用错误的正常实现。

关于swift - SearchController 不显示程序化的 collectionView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com