在 MapKit 视图控制器中添加搜索栏和定位按钮可以通过以下步骤实现:
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var locationButton: UIButton!
extension YourViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// 处理用户搜索的地点
}
}
extension YourViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.last else { return }
let region = MKCoordinateRegion(center: currentLocation.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
yourMapView.setRegion(region, animated: true)
}
}
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
@IBAction func centerMapOnUserButtonTapped() {
yourMapView.setCenter(yourMapView.userLocation.coordinate, animated: true)
}