在Apple的iOS Reminders应用程序中,您可以设置一个位置区域,提醒您提醒您。设置位置区域时,您可以绘制一个圆圈,覆盖您要提醒的位置区域。我该如何复制此功能。我特别想知道如何允许用户通过在圆的边缘拖动他的手指来调整地图视图上的圆的大小。我已经想出了如何创建圆圈。
到目前为止,这是我的代码:
import UIKit
import MapKit
class ViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var mapView: MKMapView!
// MARK: - Variables and Constants
let regionRadius: CLLocationDistance = 1000
let circularRegionRadius: CLLocationDistance = 500
let locationManager = CLLocationManager()
// MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
centerMapOnLocation(location: locationManager.location!)
}
// MARK: - Actions
@IBAction func addRegion(_ sender: UILongPressGestureRecognizer) {
print("addRegion(_:)")
let longPress = sender
let touchLocation = longPress.location(in: mapView)
let coordinates = mapView.convert(touchLocation, toCoordinateFrom: mapView)
let region = CLCircularRegion(center: coordinates, radius: circularRegionRadius, identifier: "geofence")
mapView.removeOverlays(mapView.overlays)
locationManager.startMonitoring(for: region)
let circle = MKCircle(center: coordinates, radius: region.radius)
mapView.add(circle)
}
// MARK: - Helper Functions
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
// MARK: - Memory Warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
print("mapView(_:rendererFor:_:)")
guard let circelOverLay = overlay as? MKCircle else {return MKOverlayRenderer()}
let circleRenderer = MKCircleRenderer(circle: circelOverLay)
circleRenderer.strokeColor = .blue
circleRenderer.fillColor = .blue
circleRenderer.alpha = 0.2
return circleRenderer
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager(_:didUpdateLocations:)")
locationManager.stopUpdatingLocation()
mapView.showsUserLocation = true
}
}